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

Hi Monks,

I need to check whether a given phrase is present in a text string or not. I have to check this for a number of phrases (>100 thousand phrases). All the phrases are given in a text file. What I am doing is that reading all the phrases one by one, in a variable $testPhrase and then use a regular expression to check whether this phrase is present in the text string or not. The problem is that some of these test phrases might contain certain special characters like ?,+ etc. How to prevent perl from treating them as a special character? One way is to use a regular expression for the test phrase itself and escape all the special characters that are present in the test phrase. Is there an easier/simpler way to achieve this?

For example: suppose the test phrase is c++. It is stored in $testPhrase. I need to check whether $testPhrase is present in $string or not. How to prevent perl to treat + in c++ as special characters?

Thanks for your help :-)
  • Comment on Problem using a variable for Regular expression test pattern

Replies are listed 'Best First'.
Re: Problem using a variable for Regular expression test pattern
by almut (Canon) on Jun 18, 2010 at 13:59 UTC
    How to prevent perl from treating them as a special character?

    quotemeta, or \Q.

Re: Problem using a variable for Regular expression test pattern
by jwkrahn (Abbot) on Jun 18, 2010 at 18:49 UTC
    if ( index( $string, $testPhrase ) >= 0 ) { print "\$testPhrase is present.\n"; }
Re: Problem using a variable for Regular expression test pattern
by sumit (Initiate) on Jun 21, 2010 at 11:27 UTC
    Thanks :) \Q did the trick :)