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

I've got a regular expression that checks to see if a string contains a particular word (very basic of course), here it is:
$exclude = "middle_name pager zip"; if($exclude !~ m/pager/gi) { #do its thing }
Now by all reasonable thinking, the above expression should fail, after all $exclude contains the word pager. Unfortunately it passes quite nicely and does nasty things. However, if $exclude contains
"middle_name zip pager"
the test fails exactly as it should. The only difference (and I assume the important one), is that pager comes at the end of the list rather than in the middle. I just tried m/.?pager.?/ig and that didn't work either.

Does perl have some subtle spite against pagers that I'm not aware of? Or is there some blindingly obvious problem that I'm too retarted to notice?
Thanks

Replies are listed 'Best First'.
Re: This is just wonky...
by premchai21 (Curate) on Aug 07, 2001 at 02:03 UTC
    Why the /g modifier? /g returns a list of all matches in list context and tries to match from the previous position in scalar context. That can mess you up if that's not what you're trying to do. Remove the g.
      Okay, removing the /g did get rid of the problem. I use the /g habitually as I use s/// more than m// so I didn't even consider it.

      It's still kind of weird though, and it would have really stunk if I had wanted to do a word count, but I'll get mad at that later ;)

      Thanks for the help
Re: This is just wonky...
by aquacade (Scribe) on Aug 07, 2001 at 02:12 UTC
    This is interesting! I see your point! I'm trying more tests now...Got it I hope!

    Update: Ok, my wonky guess is that the pattern match returns a null string (not undef) from the '!~' which in an if statement is FALSE of course!

    I think the index function technique may be faster if you're not using other pattern matching metacharacters. Run below to see what I think may explain the problem.

    use strict; my $exclude = 'middle_name pager zip'; my $lookfor='pager'; my $lookfor2='wonk'; # This would work without using pattern matching: # Note lc function used to ignore case! my $pos=index(lc($exclude),lc($lookfor),0); if ($pos > -1) {print "Found $lookfor !\n";} $pos=index(lc($exclude),lc($lookfor2),0); if ($pos == -1) {print "Cannot find $lookfor2 !\n";} print "\n"; my $look=($exclude =~ /$lookfor/gi); my $look2=($exclude =~ /$lookfor2/gi); my $notlook=($exclude !~ /$lookfor/gi); my $notlook2=($exclude !~ /$lookfor2/gi); print "'\$exclude =~ /$lookfor/gi' evaluates to '$look'\n"; print "'\$exclude =~ /$lookfor2/gi' evaluates to '$look2'\n"; print "'\$exclude !~ /$lookfor/gi' evaluates to '$notlook'\n"; print "'\$exclude !~ /$lookfor2/gi' evaluates to '$notlook2'\n"; __END__

    ..:::::: aquacade ::::::..