|P is for Practical|
Quote and Quote-like Operatorsby Xiong (Hermit)
|on Dec 15, 2011 at 10:10 UTC||Need Help??|
perlop contains a rather lengthy section, Quote and Quote-like Operators, containing a detailed explanation of these related constructs. You may wish to review Regexp Quote-Like Operators, Quote-Like Operators, and Gory details of parsing quoted constructs, all in the same document. This node contains an extremely brief summary, with examples.
In the listings that follow, #: indicates the output of the preceding code.
Quoting String Literals
In the most common case, we wish to store or print a simple string literal as is. The single quotes merely limit the string:
This works well enough except when the literal string must contain, literally, the single-quote character itself. Then we may escape the troublesome characters or use generic quotes:
If we need just a literal backslash then we need to escape it, too; otherwise perl will think we're trying to escape the trailing delimiter:
It's irrelevant which delimiters we use in a generic quoting construct except that, obviously, we're better off choosing delimiters that aren't in our string. Other than that, it's a matter of style. Different programmers prefer different delimiters:
Sometimes we just use generic quotes for clarity, even when plain single quotes would work as well:
Sometimes we want to mix in variable values or escape sequences; then we use interpolation. The double quotes are the most common:
The previous issues come up with interpolating quotes, too; if we want to include a double-quote character, literally, we need to use generic interpolating quotes:
And again, we can use any delimiters we like.
Common escape sequences
Many, many other escape sequences are possible; see perlop.
As a last resort, peculiar or long strings can be quoted with a heredoc construct:
If you don't single-quote the word 'HERE' in the example above, the heredoc will interpolate, much like double quotes.
Heredocs are ugly and confusing, best avoided... unless there's no better way.
Quoting a List
We may want to create a list of quoted strings, perhaps to store in an array. These statements are equivalent:
Again, any delimiters may be used with the quote word operator. But please don't make foolish choices.
Other Quote-like Constructs
Regular expressions may be considered quoting, interpolating constructs. Before any matching is done, the contents of a regex will be expanded much as if it were enclosed in double quotes:
Note that in the example above, $regex was assigned the value obtained by simple single-quoting a literal a|b|c. It's also possible to use two other constructs, quote regex and quotemeta:
Benefits to using qr// instead of q// or qq// include compile-time checking and possible optimization.
Using quotemeta on a string escapes the characters that might be special:
If you've used backticks to do a system call, you might like to know that there is also a generic backtick operator: