Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

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
[Discipulus]: good thread LanX! I completely missed it

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (8)
As of 2018-03-19 11:40 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (239 votes). Check out past polls.