Item 13: Don't misquote.Perl gives you a plethora of different ways to quote strings. There are single quotes, where everything is left "as-is" except for escaped backlashes and single quotes:
Double quotes, on the other hand, support all kinds of escape sequences. There are the usual \t , \n , \r , etc. from C, as well as octal and hex ASCII escapes like \101 and \x41 :
Double quotes also support the interpolation of the contents of variables and subscript expressions beginning with $ and @ . The elements of arrays and slices are interpolated by joining them with the contents of the $" special variablenormally a single space:
There are also escapes ( \u , \U , \l , \L , \E ) that change the case of characters following them:
I haven't begun, and I won't attempt, to cover all the nuances of double-quote interpolation in this Item. A full description, with all the gory details, can be found in the perlop man page. Alternative quoting: q , qq , and qwSometimes it is helpful to be able to use characters other than single or double quotes to enclose strings. So, naturally, Perl allows you to use any punctuation character to enclose strings. Just prefix your favorite character with q for a single-quoted string, or qq for a double-quoted string:
If you use a matchable delimiter (either ( , [ , < , or { ), then the end of the string is the corresponding closing delimiter. Perl keeps track of nesting when looking for the closing delimiter:
This is especially handy when dealing with Perl source code in quotes ( generally as an argument for eval see Item 54): Use q{ } and/or qq{ } to quote source code.
Finally, as a shorthand way of creating a list of strings, you can quote with qw ("quote words"). A string inside qw quotes is split on whitespace, returning a list of strings:
Please don't make the mistake of unintentionally including commas inside qw quotes: Don't put commas inside qw quotes.
Alternative quoting: here doc stringsPerl's "here doc" or " here document" strings provide yet another way to quote text. Many of you may be familiar with here docs alreadyPerl's here doc feature is derived from the Unix shell feature of the same name. A here doc string begins with << followed by an identifier and ends when that identifier appears on a line all by itself somewhere later in the text. The string begins on the line after << . If the identifier is quoted (with single, double, or back quotes), the type of quotes determines the type of string enclosed in the here doc. The default is a double-quoted string:
Here docs are useful for quoting long passages of text or source code. I use them frequently when writing CGI scripts. See Item 58 for more discussion about double-quote interpolation. |