雙引號

雙引號字串使用插值轉義 - 與單引號字串不同。要雙引號字串,請使用雙引號 "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"