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

I want to use pattern-matching operators with the pattern stored in a variable, e.g. m/$pattern/, s/$pattern/$replacement/. The problem is that the patterns may include characters (like brackets) which are special in regular expressions, thus causing an undesired result. What would be the best way to handle this problem?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How to prevent metacharacter interpolation
by jmcnamara (Monsignor) on Mar 14, 2001 at 15:36 UTC
    Use either the quotemeta function:
    $pattern = quotemeta( $pattern ); m/$pattern/;
    or use the \Q and \E escape characters:
    m/\Q$pattern\E/;
    They do exactly the same thing; just one is a function and the other works inside regex patterns.
Re: How to prevent metacharacter interpolation
by busunsl (Vicar) on Mar 14, 2001 at 15:37 UTC
    Use the quotemeta function:
    quotemeta($pattern); s/$pattern/$string/;

    Originally posted as a Categorized Answer.

Re: How to prevent metacharacter interpolation
by lhoward (Vicar) on Mar 14, 2001 at 18:24 UTC
    If you're just looking to search or search/replace a string and you don't need any special regular expression (regex) capabilities, you could use index or index+substr instead of m// or s///.
Re: How to prevent metacharacter interpolation
by mirod (Canon) on Mar 14, 2001 at 15:28 UTC

    The simplest might be just to prefix all non-word and non-space characters in the pattern by a \:

    $pattern=~ s/([\W\S])/\\$1/g;

    Originally posted as a Categorized Answer.