http://www.perlmonks.org?node_id=6100

Kozz has asked for the wisdom of the Perl Monks concerning the following question: (regular expressions)

In the example below, the results are I found a match: "a" I found a match: "b" There was no match for "a+b" Now, the problem is that the + in the third key of the hash is being interpreted as a description of the regular expression, not as a literal character. If I have a large hash which contains these types of meta-characters in the keys, how do I escape those meta-characters to prevent them being interpreted?
#!/usr/bin/perl my %hash=( 'a', '2', 'b', '5', 'a+b', '7', ); my $string='a+b'; my $key; foreach $key (keys %hash){ if($string=~/$key/){ print "I found a match: \"$key\"\n"; }else{ print "There was no match for \"$key\"\n"; } }

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I escape meta-characters in a user-defined string?
by btrott (Parson) on Mar 25, 2000 at 01:05 UTC
    if($string=~/\Q$key\E/){
    Quotes the metacharacters.