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

Greetings all,
I'm working on a log parsing project and am trying to modify one of the scripts, but it's giving me some fits that I can't figure out. The code:
if (length($_)>10) { $readlines++;

This is the original. It's an arbitrary lenght check. If the log line is at least 10 characters, it'll pass. What I need to do is add a secondary check to verify that the log line contains one of our IP addresses. Here's what I've tried:
if (length($_)>10) { if ($_ =~ (m/192\.168\./g)) { $readlines++;

But what happens is that I only ever have one line accepted. If I run the original script, I had 10,000 lines accepted. With this mod, the identical content only has one line accepted.
Suggestions?
Thanks,
monger
Monger +++++++++++++++++++++++++ Munging Perl on the side

Replies are listed 'Best First'.
Re: Pattern Matching Again - IP Addy
by ikegami (Patriarch) on Nov 17, 2004 at 21:24 UTC

    hum, it works for me...

    while (<DATA>) { if (length($_) > 10) { if ($_ =~ (m/192\.168\./g)) { $readlines++; } } } print($readlines, $/); # prints 3, although you're probably expecting it to be 2. __DATA__ 192.168.0.1 1.192.168.0 12345678901 dfhasfhasdjk 192.168.33.4

    The /g is unecessary, misleading, and a potential cause of problem. The $_ is the default argument for both length and m//, so it can be omitted:

    while (<DATA>) { if (length && /192\.168\./) { $readlines++; } } print($readlines, $/); # prints 3, although you're probably expecting it to be 2. __DATA__ 192.168.0.1 1.192.168.0 12345678901 dfhasfhasdjk 192.168.33.4
      Thanks ikegami. That did the trick!
      monger
      Monger +++++++++++++++++++++++++ Munging Perl on the side
Re: Pattern Matching Again - IP Addy
by NetWallah (Canon) on Nov 17, 2004 at 21:26 UTC
    You are giving the regex a list context - that is messing you up.

    Update:Nope - the RE works fine, but ikegami's is better.

        Earth first! (We'll rob the other planets later)