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

I'm trying to grab each line from sendmail syslog file and combine the different lines where the message id's are the same and combine them to show source and destination.
p3D8Bj1f007915 user1@domain.com p3D8EF8n007918 user2@domain.com p3D8Bj1f007915 server101@domain.com p3D8EF8n007918 server111@domain.com
My goal is the have one hash with output like:
p3D8Bj1f007915 user1@domain.com sent message from server101@domain.com p3D8EF8n007918 user2@domain.com sent message from server111@domain.com
So far, the code below only produces two simple hashes that are only uniq by msgid:
#!/bin/perl open (FH, "/var/log/syslog") ; foreach $lin (<FH>) { chomp($lin) ; next unless $lin !~ /^\s*$/ ; # Gets rid of blank lines if ($lin =~ /sendmail-listen/){ $lin =~ s/<// ; #removes < from the line $lin =~ s/>,// ; #removes > from the line ($a,$b,$c,$d,$e,$msgid,$g)=split(' ',$lin) ; $msgid =~ s/:// ; #print $g,"\n"; #make sure i'm grabbing the to= and the fr +om= for the follow $destname #TO if ($g =~ /^to/){ ($to,$destname)=split('=',$g) ; $destname =~ s/,// ; chomp($destname) ; $to{$msgid} = $destname ; #Two scalar values going into a + hash called $to. } #FROM if ($g =~ /^from/){ ($fr,$fromname)=split('=',$g) ; $fromname =~ s/,// ; chomp($fromname) ; $from{$msgid} = $fromname ; #Two scalar values going into + a hash called $from. } } #ENDS sendmail-listen + + } close ( FH ) ; #print the $to hash foreach $too (sort keys %to) { print "$too $to{$too}\n"; } #print the $from hash foreach $fromm (sort keys %from) { print "$fromm $from{$fromm}\n"; }
Thanks for looking!

Replies are listed 'Best First'.
Re: sendmail logging combine two hashes
by hdb (Monsignor) on Feb 18, 2015 at 11:23 UTC

    You could combine your data into one hash %msg when you read the file instead of creating two hashes:

    $msg{$msgid}{'to'} = $destname; $msg{$msgid}{'from'} = $fromname;
      Thank you! I'm looking at Data::Dumper to figure how to print!

        Try

        for my $m (keys %msg) { print "$m $msg{$m}{to} send message from $msg{$m}{from}\n"; }
Re: sendmail logging combine two hashes
by johngg (Canon) on Feb 18, 2015 at 14:10 UTC
    next unless $lin !~ /^\s*$/ ;

    I wonder why you are using a sort-of coding double negative here. Wouldn't

    next if $lin =~ /^\s*$/;

    be easier for human readers to parse? Just curious as to your thinking :-s

    Cheers,

    JohnGG

      Hello, Thanks for speaking out! I'm eager to learn and listening! So my thought should be - next if the line is blank! Thanks, I'm working to become a better perl scripter! :)
      #next unless $lin !~ /^\s*$/ ; # Gets rid of blank lines next if $lin =~ /^\s*$/ ; # Gets rid of blank lines, Thanks JohnGG@pe +rlmonks