I’m using Perl 5.10.6 on Mac 10.6.6. I want to execute a simple search and replace against a file so I tried:
my $searchAndReplaceCmd = "perl -pi -e 's/\\Q${localTestDir}\\E//g' ${testSuiteFile}";
system( $searchAndReplaceCmd );
but the problem above is the variable $localTestDir contains directory separators ("/"), and this screws up the regular expression …
Bareword found where operator expected at -e line 1, near
“s/\Q/home/selenium”Backslash found where operator expected at -e
line 1, near “Live\” syntax error at -e line 1, near
“s/\Q/home/selenium”Search pattern not terminated at -e line 1.
How do I do a search and replace on a file when the variable in question contains regular expression characters? Thanks.
Question is why you do a search and replace from within perl, through the shell, within perl. Seems like a roundabout way of doing things, and you’ll run into problems with shell interpolation.
The
\Q ... \Eshould override the special characters in your string, so/“should” not be an issue. From perlre:Here’s an alternative (untested), all perl solution. If you want to be extra certain, exchange the
/delimiter to something else, such ass###(you can use any character as a delimiter).Or use Tie::File