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

Hi monks!
I am running a patttern match programm and there is a possibility that some of the strings I want to match against other strings, may contain special characters, like \| or . or +
Is there any way I can ,somehow, "escape" the whole string before I put it inside // ?
For example, I wanted to match a pattern like |123456|john+ against a string and it didn't work, because it used the | and + in the pattern matching, while I just wanted them to appear as normal + and |
So, I am asking if there is such a way to escape all things at once, because I don't know beforehand if my pattern will have | or + or .
Any hints?

Replies are listed 'Best First'.
Re: escape all special characters???
by eff_i_g (Curate) on May 10, 2006 at 21:55 UTC
    quotemeta.

    You can also place data between \Q and \E to selectively escape parts instead of the whole; see perlre.
      My God!!! Thank you so much!!! Iw works fine... And, imagine I had just been trough Perl manfunc, and I didn't notice this function... Although I was actually searching to escape all special characters... Thanks again for your help!
Re: escape all special characters???
by gellyfish (Monsignor) on May 10, 2006 at 21:59 UTC

    You can use the \Q and \E pair of escape sequences to stop and restart interpretation regular expression metacharacters. So you could have something like:

    $string =~ /\Q|123456|john+\E/;

    /J\

Re: escape all special characters???
by ikegami (Patriarch) on May 10, 2006 at 22:14 UTC
    Here are sample usages of the aformentioned:
    • $string = '|123456|john+'; /\Q$string\E/ # Strings are still interpolated, # but their contents are escaped.
    • $string = '|123456|john+'; /\Q$string/ # The \E is optional
    • /\Q|123456|john+\E/ # As long as the text doesn't # contain "$", "@", the regexp # delimiter (which is "/" here) # or \E.
    • $string = quotemeta('|123456|john+'); /$string/