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

With the disclaimer that I'm relatively new at this:
Check out the simple code below:
$string = "abcd"; # $input = "d"; OK # $input = "("; ERROR if($string =~ m/($input)/){ print "The string is $string\n"; }

My problem is that the variable $input can be anything, including metacharacters (I'm trying to do some compiler stuff).
How can the code be changed to check any input?
Thanks
-tl

Replies are listed 'Best First'.
Re: Problems with matching and metacharacters
by WebHick (Scribe) on Jun 14, 2001 at 19:00 UTC

    Simply put \Q and \E around $input. Like so:
     m/(\Q$input\E)/

    Don't do this:
    m/\Q($input)\E/
    Because the regex will also try to match the parenthesis.

    Sarah
    Update: I never said I was fast.

      Actually, the \E is not needed, since $input is the only thing in the regex; that is, it is automatically ended.
      /(\Q$input)/
      Here's a question: Why would you need to put parentheses around $input? You can access its value more efficiently as $input, than as $1, since parentheses would slow down the regex. More succintly, change the code to this:
      /\Q$input/
      And change occurences of $1 to $input

        Actually, /(\Q$input)/ produces the error:

        /(\(\)/: unmatched () in regexp

        because you're now matching $input), not just $input. If the parenthesis are to stay, you'll need the \E

        Sarah

Re: Problems with matching and metacharacters
by VSarkiss (Monsignor) on Jun 14, 2001 at 18:57 UTC
    Not sure if this is what you're looking for, but quotemeta will return its argument string with all metacharacters quoted (preceded by backslashes, in case that's relevant). Take a look at perlfunc.

    HTH