在 Perl 中,双引号 (")、单引号 (') 和重音符 (`) 之间有什么区别

use*_*381 -3 perl operators

在 Perl 中,用双引号 (")、单引号 (') 和重音符 (`) 引用有什么区别?

这段代码:

#!/bin/env perl
use v5.10;
say "Hello";
say 'Hi';
say `Hola`;
Run Code Online (Sandbox Code Playgroud)

给出以下结果:

你好
你好

sim*_*que 5

单引号 ''

构造没有插值的字符串。还有一个q()操作符可以做同样的事情。

my $foo = 'bar';
print '$foo'; # prints the word $foo
print q($foo); # is equivalent
Run Code Online (Sandbox Code Playgroud)

当您只有文本并且文本中没有变量时,您将使用单引号。

双引号 ""

用变量插值构造字符串。还有一个qq()操作符可以做同样的事情。

my $foo = 'bar';
print "$foo"; # prints the word bar
print qq($foo); # is equivalent
Run Code Online (Sandbox Code Playgroud)

如果您想将变量放入字符串中,请使用这些。一个典型的例子是在一个老式的 CGI 程序中,你会看到这个:

print "<td>$row[0]</td>";
Run Code Online (Sandbox Code Playgroud)

qq()如果您的文本包含双引号,则该变体会派上用场。

print qq{<a href="$url">$link_text</a>}; # I prefer qq{} to qq()
Run Code Online (Sandbox Code Playgroud)

这比转义所有引号更容易阅读。

print "<a href=\"$url\">$link_text</a>"; # this is hard to read
Run Code Online (Sandbox Code Playgroud)

反引号 ``

脱壳并执行命令。返回另一个程序的返回值。还有一个qx()操作符可以做同样的事情。这会插入变量。

print `ls`; # prints a directory listing of the working directory
my $res = qx(./foo --bar);
Run Code Online (Sandbox Code Playgroud)

如果您想编写一个比 shell 脚本更强大的脚本,您需要调用外部程序并捕获它们的输出,请使用此选项。


所有的插值只能对变量进行插值,不能对命令进行插值。

my $foo = 1;
my $bar = 2;
print "$foo + $bar";
Run Code Online (Sandbox Code Playgroud)

这将打印1 + 2。它实际上不会计算和打印3


所有这些(以及更多)都Quote 和 Quotelike 操作符下的perlop 中进行了解释。

  • @choroba 每次有人编辑我的一个错别字时,我都会有一种温暖的模糊感觉,人们实际上是在阅读我的东西:D (2认同)
  • 每次你在 SO 上打错字,你都会杀死别人的脑细胞 :-) (2认同)