http://www.perlmonks.org?node_id=750168

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

Hi Monks, I have a little program file that's meant to search itself for lines which contain a specific word which is the first word in line 3 (ie $testVar). For some reason it does not work. Anyone clues as to how to make this work?
### this file is called regex.pl my $testVar; $testVar = "January"; ### read this file open(FH,"<regex.pl") or die "cannot open file"; my @myself = <FH>; close(FH); ### make $pattern: $testVar $myself[2]=~/([^ ]+)/; my $pattern = $1; print "Pattern: $pattern\n"; ### print lines with this pattern for(@myself) { print if /$pattern/; }
Thanks.

Replies are listed 'Best First'.
Re: regex search fails
by jethro (Monsignor) on Mar 12, 2009 at 14:39 UTC

    Change the line in the loop to

    print if /\Q$pattern\E/;

    This is equivalent to $pattern= quotemeata($pattern); before the loop. The '$' in your pattern is interpreted as special char in your regex, thats why it isn't working

      If the "solution" is
      print if /\Q$pattern\E/;
      then $pattern doesn't contains a regexp pattern as its name implies. The variable should be renamed
      my $search_str = $1; ... print if /\Q$search_str/;
      or quotemeta should be called earlier.
      my $pattern = quotemeta($1); # aka "\Q$1" ... print if /$pattern/;
Re: regex search fails
by friedo (Prior) on Mar 12, 2009 at 14:41 UTC
    Try print if /\Q$pattern/. Since your pattern contains the literal string '$testVar', using the \Q escape will prevent it from being interpolated in the match.
      Thanks everyone. The \Q did the trick.