carenas2 has asked for the wisdom of the Perl Monks concerning the following question:

In a script, I read pairs of strings in a config file and store them in a hash. Subsequently I loop through lines of text, searching for the hash keys and replacing with the corresponding values (ie, $text =~ s/$key/$val/).

The strings I am dealing with can contain metacharacters, such as parentheses, periods, etc., as well as non-ASCII characters. In these cases, my s/// doesn't work.

I was hoping to find a way to programmatically sanitize these strings for use as regexes, so that metacharacters are escaped and non-ASCII characters are properly dealt with.

I have searched but found no solution. Can someone point me in the right direction? TIA.

Replies are listed 'Best First'.
Re: Sanitizing strings as regexes
by mr_mischief (Monsignor) on Oct 10, 2008 at 16:55 UTC
    Look at \Q and \E in perlre.
    $string = '(.asdf[0-9])$'; $foo = '(.asdf[0-9])$'; if ( $foo =~ m/$string/ ) { print "won't work\n"; } if ( $foo =~ m/\Q$string\E/ ) { print "will work\n"; }