Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

regex search fails

by stephanm (Sexton)
on Mar 12, 2009 at 14:17 UTC ( #750168=perlquestion: print w/replies, xml ) Need Help??
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 my $testVar; $testVar = "January"; ### read this file open(FH,"<") 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/; }

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://750168]
Approved by friedo
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2018-01-17 00:22 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (194 votes). Check out past polls.