in reply to Process mail logs

An interesting alternative if you need non-trivial processing for each operation is to use a dispatch table. Consider:

#!/usr/bin/perl use strict; use warnings; use 5.010; my %ops = ('==' => \&doEq, '=>' => \&doGe, '<=' => \&doLe, '**' => \&d +oStar,); my $opMatch = join '|', map {qr{\Q$_\E}} keys %ops; while (my $line = <DATA>) { chomp($line); my ($op) = $line =~ m{\s($opMatch)\s}; if ($op) { $ops{$op}->($line); } else { print "No op found: $line\n"; } } sub doEq {my ($line) = @_; print "Do da ==: $line\n";} sub doLe {my ($line) = @_; print "Doing <=: $line\n";} sub doGe {my ($line) = @_; print "Doing =>: $line\n";} sub doStar {my ($line) = @_; print "Process **: $line\n";} __DATA__ 1234 <= inb@it.com 1234 <= inb@it.com 1235 => pp <pp@nsd.net> 1235 ++ pp <pp@nsd.net>

Prints:

Doing <=: 1234 <= inb@it.com Doing <=: 1234 <= inb@it.com Doing =>: 1235 => pp <pp@nsd.net> No op found: 1235 ++ pp <pp@nsd.net>
True laziness is hard work

Replies are listed 'Best First'.
Re^2: Process mail logs
by stevbutt (Novice) on Aug 13, 2012 at 14:53 UTC

    Ok I think I have pieced together a solution but would appreciate one last ( hopefully ) piece of wisdom.

    the host section of the log can look like any of the following examples

    blah blah H=(10.21.32.43) [192.168.8.34] blah blah blah H=([10.21.32.43]) [192.168.8.34] blah blah blah H=mailsrvr.mail.com [192.168.8.34] blah

    The data I want to assign is the number in the square brackets i.e. 192.168.8.34

    How would I go about pattern matching to extract this i.e ip address in square brackets after space following initial text following H=

    Many Thanks, Steve

      If you plan on using Perl for more than a day or two I strongly recommend you read through the regular expression documentation provided with Perl (see perlretut, perlre and perlreref). Perl is strong on text processing and a large chunk of that comes from using regular expressions so understanding Perl's regular expression is important to writing good Perl code.

      For this particular match you could make it more or less fussy (like mathing the () part or not). A somewhat non-fussy match would be /H=[^[]* \[ ([^\]]+) \]/x. Note the use of the x flag to allow white space in the expression so it's easier to see the various moving parts.

      True laziness is hard work

        Thank you very much for the help

        I have been reading the regex docs as I go but its difficult without experience to know what an efficient way to do these things is

        Again, Many Thanks, Steve