Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

regexp bug

by kidd (Curate)
on Aug 27, 2002 at 13:36 UTC ( #193153=perlquestion: print w/replies, xml ) Need Help??
kidd has asked for the wisdom of the Perl Monks concerning the following question:

hello monks...

I have this code that makes a search trough a lot of texts. I finished it and I tested but the I saw something, when I searched for lets say "foo" it returned true to either "foo" and "foobar"... I didnt want that! I wanted only to be true to "foo" nothing more nothing less.

So, I decided to make a correction and I edited this line:

my $count = grep{ /$query/ } $_;
my $count = grep{ /\b$query\b/ } $_;

But I test it and sometimes it works fine and other times it doesnt...Can someone tell me what Im doing wrong...

And if you could tell me how can I make the search not case-sensitive...

I thought that maybe I could do that like this:

my $count = grep{ /\b$query\b/i } $_;


Replies are listed 'Best First'.
Re: regexp bug
by hotshot (Prior) on Aug 27, 2002 at 15:24 UTC
    But I test it and sometimes it works fine and other times it doesnt

    can you give us some examples? (on what strings it works and when it doesn't work).

Re: regexp bug
by thelenm (Vicar) on Aug 27, 2002 at 17:10 UTC
    As hotshot said, giving examples of how it's failing will be very helpful. Please give some examples of input you're giving it and output you expect.

    It's not clear what $count is supposed to be, but it will actually be either 0 or 1 depending on whether the pattern matches $_. If you want a true count of the number of matches, you should do something like this instead:

    $count = () = /\b\Q$query\E\b/ig;
    I put the \Q and \E in there even though "foo" doesn't contain any special regex characters, because it guards against accidents if you search on something besides "foo" later. And you're correct to use /i to do a case-insensitive match.

    -- Mike


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (10)
As of 2018-06-25 12:41 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.