# Perl Backslash in Regular Expression

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";$str =~ s/$a/$b/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$a\E/$b/g;    # this prints d:\bar\test

Now we get what we expected.