Perl Escape Backslashes in String Substitution

This note is for a trick to use Q and E  to escape characters for regular expression. You will find it very useful when you do string substitution and your pattern contains characters like slashes or backslashes .

Here is an example example,  in following code we try to replace c:foo to d:bar for a given directory name.

my $dir = “c:\foo\test”;
my $foo = ” c:\foo”;
my $bar = ” d:\bar”;
$dir =~ s/$foo/$bar/g;    # this prints c:footest

The code will not work as backslashes are escaped to \ in regular expression pattern, after using Q and E to escape backslashes in pattern,

my $dir = “c:\foo\test”;
my $foo = “c:\foo”;
my $bar = “d:\bar”;
$str =~ s/Q$fooE/$bar/g;    # this prints d:bartest

Now we get what we expected.

More information can be found at

http://www.sdsc.edu/~moreland/courses/IntroPerl/docs/manual/pod/perlre.html

E end case modification (think vi)

Q quote (disable) pattern metacharacters till E

Leave a Reply

Your email address will not be published.