Working through “Learning Perl” I’ve got a problem with strings. Specifically the difference b/t single-quoted and double-quoted strings and the use of the backslash character.
In the Single-quoted strings section it says that, “Any character other than a single quote or a backslash between the quote marks (including newline characters, if the string continues onto successive lines) stands for itself inside a string. To get a backslash, put two backslashes in a row, and to get a single quote, put a backslash followed by a single quote.”
I tried the following:
print ‘Testing\z’;
print ‘Testing\\n’;
print ‘Testing\\\n’;
print “\n”;
And get:
erikweibust@daleweibust ~/perl/lrn_perl $ ./test1-2.pl
Testing\nTesting\nTesting\\n
erikweibust@daleweibust ~/perl/lrn_perl $
So I’m scared that either the books wrong (please don’t get the wrath of Randal Schwartz) or I’m missing something. I would have expected the output to be:
erikweibust@daleweibust ~/perl/lrn_perl $ ./test1-2.pl
TestingnTesting\nTesting\n
erikweibust@daleweibust ~/perl/lrn_perl $
Can anybody help clear this up?
I posted this same question on perlmonks and got a number of great answers. This one helpped the most and I’m copying the answer below.
Answer from PerlMonks.org:
OK, first off, I’m a bit confused, because your first line says ‘Testing\z’. Perhaps you meant ‘Testing\n’ ?
With that out of the way, you are missing something — or rather, the document you just quoted is missing something.
It handles three cases:
1. Any character OTHER than a backslash or termination character is inserted literally. (The termination character is normally ‘ but may differ if q// is used.)
2. Any backslash followed by the termination character inserts the termination character.
3. Any backslash followed by a backslash inserts a backslash.
What it doesn’t tell you is the fourth case:
4. Any backslash followed by a character OTHER than the termination character or a backslash inserts a backslash and that literal character.
The reason for the double-backslash thing is in case you wanted to include a backslash at the end of the string.
For example:
$foo = ‘C:\\’;
# if you had ‘C:\’ then the ‘ would instead be
# escaped instead of ending the string.
—Stevie-O