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

Here is my dilemma:

I need to search for the phrase: !CCSD(T) STATE 1.1 ENERGY in a text file.

simply enough, I can use the matching operator as such:
$_ =~ m/'!CCSD\(T\) STATE 1.1 ENERGY'/
The string is matched and all is well.

The complication comes in because I need to read the phrase from a different text file. Once the phrase is parsed from the text, I store it in a variable called $flag.

I, then, use the matching operator this way:
$_ =~ m/$flag/
The string never matches.

I have tried every conceivable combination of quotes and backslashes without any luck. How can I get this rather seemingly routine thing to work?

Replies are listed 'Best First'.
Re: string matching
by FunkyMonk (Chancellor) on Sep 21, 2007 at 18:27 UTC
    Have you tried quotemeta on the pattern you read from a file? There's also a version of quotemeta that works inside your match: $_ =~ m/\Q$flag/

    Update: Are you remembering to chomp the line from the file?

      It worked!
      You are a genius!
Re: string matching
by kyle (Abbot) on Sep 21, 2007 at 19:09 UTC

    FunkyMonk's suggestion of using quotemeta (and \Q) should work well. If you really are looking only for literal strings, though, it might be better to use index for that. Also, your original matching pattern contains a dot (/./) which will match any character (except newline), so /1.1/ will also match "1x1", for example. You need to quote the dot to make it literal (i.e., /\./).

Re: string matching
by Anno (Deacon) on Sep 21, 2007 at 21:26 UTC
    You could use quotemeta() to make the regex work, as has been noted. Since you are searching for a fixed string, the index() function offers itself as a simpler tool that does the job. There is no need to quote anything because index() treats all characters equal.
    if ( index( $_, $flag) >= 0 ) { # found it
    Anno