Perl中单引号和双引号之间的区别是什么?

时间:2010-01-08 14:28:07

标签: perl syntax interpolation

我刚开始学习Perl。我查看beginning perl page并开始工作。

它说:

  

单引号和双引号之间的区别在于单引号表示其内容应按字面意思理解,而双引号表示其内容应解释

当我运行此程序时:

#!/usr/local/bin/perl
print "This string \n shows up on two lines.";
print 'This string \n shows up on only one.';

输出:

This string
 shows up on two lines.
This string
 shows up on only one.

我错了吗? perl的版本如下:

perl -v

This is perl, v5.8.5 built for aix

Copyright 1987-2004, Larry Wall

Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.

Complete documentation for Perl, including FAQ lists, should be found on
this system using `man perl' or `perldoc perl'.  If you have access to the
Internet, point your browser at http://www.perl.com/, the Perl Home Page.

6 个答案:

答案 0 :(得分:15)

我倾向于说你的shell /终端有什么问题,无论你输出什么,都将\ n解释为换行符,并且问题不在于Perl。

要确认:这不应该发生(TM) - 在第一种情况下,我希望看到插入一个新行,但是使用单引号时,它应该输出字符 \ n 换行。

答案 1 :(得分:4)

在Perl中,单引号字符串不会扩展反斜杠转义符,例如\n\t。你看到它们扩展的原因可能是由于你正在使用的shell的性质,这是出于某种原因使你的输出变得混乱。

答案 2 :(得分:3)

关于引用和类似报价的运算符,您需要了解的所有内容都在perlop

要回答您的具体问题,双引号可以将某些文字字符序列转换为其他字符。在您的示例中,双引号将字符序列\n转换为表示换行符的单个字符。在单引号字符串中,相同的文字序列只是文字\n字符。

答案 3 :(得分:1)

通过“解释”,它们意味着不会打印变量名称等,而是打印它们的值。 \ n是一个转义序列,所以我认为它不会被解释。

答案 4 :(得分:1)

除了你的O'Reilly链接之外,一个与Larry Wall的“Programming Perl”一书相比具有权威性的参考文献指出,单引号字符串中不会出现反斜杠插值。

... much like Unix shell quotes: double quoted string literals are subject to   
backslash and variable interpolation; single quoted strings are not   
(except for \' and \\, so that you may ...)  

Programing Perl, 2nd ed, 1996 page 16

所以看看你的Perl做什么会很有趣     打印'双反斜杠n:\\ n';

如上所述,请向我们展示'perl -v'的输出。

我相信我已经混淆了论坛编辑器软件,因为最后一个Perl'print'应该缩进。

答案 5 :(得分:1)

如果使用双引号,它将被解释为\ n作为换行符。

但是如果使用单引号,则不会将\ n解释为换行符。

对我来说它运作正常。

文件内容

print "This string \n shows up on two lines.";
print 'This string \n shows up on only one.'