Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

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 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.

Comment on regex search fails
Download Code
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://750168]
Approved by friedo
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (3)
As of 2014-09-18 04:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (108 votes), past polls