双引号

双引号字符串使用插值转义 - 与单引号字符串不同。要双引号字符串,请使用双引号 "qq 运算符。

my $greeting = "Hello!\n";
print $greeting;
# => Hello! (followed by a linefeed)

my $bush = "They misunderestimated me."
print qq/As Bush once said: "$bush"\n/;
# => As Bush once said: "They misunderestimated me." (with linefeed)

qq 在这里很有用,以避免不得不转义引号。没有它,我们将不得不写…

print "As Bush once said: \"$bush\"\n";

…这不是很好。

Perl 并不限制你使用斜线/qq; 你可以使用任何(可见)字符。

use feature 'say';

say qq/You can use slashes.../;
say qq{...or braces...};
say qq^...or hats...^;
say qq|...or pipes...|;
# say qq ...but not whitespace. ;

你还可以将数组插入到字符串中。

use feature 'say';

my @letters = ('a', 'b', 'c');
say "I like these letters: @letters.";
# => I like these letters: a b c.

默认情况下,值是空格分隔的 - 因为特殊变量 $" 默认为单个空格。当然,这可以改变。

use feature 'say';

my @letters = ('a', 'b', 'c');
{local $" = ", "; say "@letters"; }    # a, b, c

如果你愿意,可以选择 use English 并改为改变 $LIST_SEPARATOR

use v5.18; # English should be avoided on older Perls
use English;

my @letters = ('a', 'b', 'c');
{ local $LIST_SEPARATOR = "\n"; say "My favourite letters:\n\n@letters" }

对于比这更复杂的东西,你应该使用循环代替。

say "My favourite letters:";
say;
for my $letter (@letters) {
  say " - $letter";
}

插值并没有与哈希工作。

use feature 'say';

my %hash = ('a', 'b', 'c', 'd');
say "This doesn't work: %hash"         # This doesn't work: %hash

一些代码滥用引用的插值 - 避免它

use feature 'say';

say "2 + 2 == @{[ 2 + 2 ]}";           # 2 + 2 = 4 (avoid this)
say "2 + 2 == ${\( 2 + 2 )}";          # 2 + 2 = 4 (avoid this)

所谓的购物车操作符会导致 perl 取消引用包含要插入的表达式的数组引用 [ ... ]2 + 2。当你使用这个技巧时,Perl 构建一个匿名数组,然后取消引用它并丢弃它。

${\( ... )} 版本的浪费要少一些,但它仍然需要分配内存,而且更难以阅读。

相反,考虑写:

  • say "2 + 2 == " . 2 + 2;
  • my $result = 2 + 2; say "2 + 2 == $result"