[英]What's the difference between single and double quotes in Perl?
我刚开始学习Perl。 我查看了开始的perl页面并开始工作。
它说:
单引号和双引号之间的区别在于单引号意味着它们的内容应按字面意思理解,而双引号意味着它们的内容应该被解释
当我运行这个程序时:
#!/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.
我倾向于说你的shell /终端有什么问题,无论你输出什么,都将\\ n解释为换行符,而问题不在于Perl。
要确认:这不应该发生(TM) - 在第一种情况下我希望看到插入一个新行,但是使用单引号它应该输出字符\\ n而不是新行。
在Perl中,单引号字符串不会像\\n
或\\t
那样扩展反斜杠转义。 你看到它们扩展的原因可能是由于你正在使用的shell的性质,这是出于某种原因使你的输出变得混乱。
您需要了解的有关引用和类似报价的运算符的所有内容都在perlop中 。
要回答您的具体问题,双引号可以将某些文字字符序列转换为其他字符。 在您的示例中,双引号将字符序列\\
和n
转换为表示换行符的单个字符。 在单引号字符串中,相同的文字序列只是文字\\
和n
字符。
通过“解释”,它们意味着不会打印变量名称等,而是打印它们的值。 \\ n是一个转义序列,所以我认为它不会被解释。
除了你的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做什么会很有趣
print'双反斜杠n:\\\\ n';
如上所示,请向我们展示'perl -v'的输出。
我相信我已经混淆了论坛编辑器软件,因为最后一个Perl'print'应该缩进。
如果使用双引号,它将被解释为\\ n作为换行符。
但是如果使用单引号,则不会将\\ n解释为换行符。
对我而言,它正常工作。
文件内容
print "This string \n shows up on two lines.";
print 'This string \n shows up on only one.'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.