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:\foo\test

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$foo\E/$bar/g;    # this prints d:\bar\test

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.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>