126.96.36.199 Special Characters in Single-quoted Strings
There are two characters in single quoted strings that do not always
represent themselves. This is due to necessity, since single-quoted
strings start and end with the `'' character. We need a way to
express inside a single-quoted string that we want the string to contain
a `'' character.
The solution to this problem is to preceded any `'' characters we
actually want to appear in the string itself with the backslash
(`\' character). Thus we have strings like this:
'xxx\'xxx'; # xxx, a single-quote character, and then xxx
We have in this example a string with 7 characters exactly. Namely,
this is the string:
xxx'xxx. It can be difficult at first to
become accustomed to the idea that two characters in the input to Perl
actually produce only one character in the string itself. (3) However, just keep
in mind the rules and you will probably get used to them quickly.
Since we have used the `\' character to do something special with
the `'' character, we must now worry about the special cases for
the backslash character itself. When we see a `\' character in a
single-quoted string, we must carefully consider what will happen.
Under most circumstances, when a `\' is in a single-quoted string,
it is simply a backslash, representing itself, as most other characters
do. However, the following exceptions apply:
- The sequence `\'' yields the character `'' in the actual
string. (This is the exception we already discussed above).
- The sequence `\\' yields the character `\' in the actual
string. In other words, two backslashes right next to each other
actually yield only one backslash.
- A backslash, by itself, cannot be placed at the end of a the
single-quoted string. This cannot happen because Perl will think
that you are using the `\' to escape the closing `''.
The following examples exemplify the various exceptions, and use them
'I don\'t think so.'; # Note the ' inside is escaped with \
'Need a \\ (backslash) or \?'; # The \\ gives us \, as does \
'You can do this: \\'; # A single backslash at the end
'Three \\\'s: "\\\\\"'; # There are three \ chars between ""
In the last example, note that the resulting string is
Three \'s: "\\\". If you can follow that example, you have
definitely mastered how single-quoted strings work!