What's the difference between single and double quotes in Perl?

Deadly 提交于 2019-12-04 08:37:35

I am inclined to say something is up with your shell/terminal, and whatever you are outputting to is interpreting the \n as a newline and that the problem is not with Perl.

To confirm: This Shouldn't Happen(TM) - in the first case I would expect to see a new line inserted, but with single quotes it ought to output literally the characters \n and not a new line.

In Perl, single-quoted strings do not expand backslash-escapes like \n or \t. The reason you're seeing them expanded is probably due to the nature of the shell that you're using, which is munging your output for some reason.

Everything you need to know about quoting and quote-like operators is in perlop.

To answer your specific question, double-quotes can turn certain sequences of literal characters into other characters. In your example, the double quotes turn the sequence of characters \ and n into the single character that represents a newline. In a single quoted string, that same literal sequence is just the literal \ and n characters.

By "interpreted", they mean that variable names and such will not be printed, but their values instead. \n is an escape sequence, so I'd think it would not be interpreted.

In addition to your O'Reilly link, a reference no less authoritative than the 'Programming Perl' book by Larry Wall, states that backslash interpolation does not occur in single quoted strings.

... 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

So it would be interesting to see what your Perl does with
print 'Double backslash n: \\n';

As above, please show us the output from 'perl -v'.

And I believe I have confused the forum editor software, because that last Perl 'print' should have indented.

If you use the double quote it will be interpreted the \n as a newline.

But if you use the single quote it will not interpreted the \n as a newline.

For me it is working correctly.

file content

print "This string \n shows up on two lines.";
print 'This string \n shows up on only one.'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!