ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
1.13. Escaping CharactersProblemYou need to output a string with certain characters (quotes, commas, etc.) escaped. For instance, you're producing a format string for SolutionUse 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
$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 $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 DOS and Windows COMMAND.COM recognizes double quotes but not single ones, has no clue what to do with backquotes, and requires a backslash to make a double quote a literal. Almost any of the free or commercial Unix-like shell environments for Windows will improve this depressing situation. Because we're using character classes in the regular expressions, we can use $string =~ s/([^A-Z])/\\$1/g; If you want to escape all non-word characters, use the $string = "this \Qis a test!\E"; $string = "this is\\ a\\ test\\!"; $string = "this " . quotemeta("is a test!"); See AlsoThe |