[英]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.