Escaping Characters
Problem
You need to output a string with certain characters (quotes, commas,
etc.) escaped. For instance, you’re producing a format string
for sprintf and want to convert literal
% signs into %%.
Solution
Use a substitution to backslash or double each character to be escaped.
# backslash $var =~ s/([CHARLIST])/\\$1/g; # double $var =~ s/([CHARLIST])/$1$1/g;
Discussion
$var is the variable to be altered. The
CHARLIST is a list of characters to escape and can
contain backslash escapes like \t and
\n. If you just have one character to escape, omit
the brackets:
$string =~ s/%/%%/g;
The following lets you do escaping when preparing strings to submit
to the shell. (In practice, you would need to escape more than just
' and " to make any arbitrary string safe
for the shell. Getting the list of characters right is so hard, and
the risks if you get it wrong are so great, that you’re better
off using the list form of system and
exec to run programs, shown in Section 16.2. They avoid the shell altogether.)
$string = q(Mom said, "Don't do that."); $string =~ s/(['"])/\\$1/g;
We had to use two backslashes in the replacement because the replacement section of a substitution is read as a double-quoted string, and to get one backslash, you need to write two. Here’s a similar example for VMS DCL, where you need to double every quote to get one through:
$string = q(Mom said, "Don't do that."); $string =~ s/(['"])/$1$1/g;
Microsoft command interpreters are harder to work with. In ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access