scryptKiddy scryptKiddy - 1 year ago 67
Perl Question

How to add values from duplicate keys in Perl hash

Every week I want to parse through the daily logs (on a Red Hat system) and get some statistics on the IP address column. The daily logs contain data with


like this:

Sample data - First 5 lines of one of the logs:


I'd like to go through all seven logs and determine the total number of packets for each IP address.

The desired output would be


sorted by packet count from all the seven logs like so:,480,400,220


I'm not quite sure if a hash is the best way to do this, and if it is, how to approach it.

Answer Source

Here's how I would do this:

my $packetCountByIP = {};
for (my $i = 1; $i <= 7; ++$i) {
    my $fileName = 'activity'.$i.'.log';
    my $fh;
    if (!open($fh,'<',$fileName)) { die("$fileName: $!"); }
    while (my $line = <$fh>) {
        my $fields = [split(',',$line)];
        my $ip = $fields->[1];
        my $packetCount = $fields->[3]+0;
        $packetCountByIP->{$ip} += $packetCount;
    } ## end while (log file lines)
} ## end for (log files)

my $ips = [sort({$packetCountByIP->{$b}<=>$packetCountByIP->{$a}} keys(%$packetCountByIP))];
foreach my $ip (@$ips) {
} ## end foreach (ips)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download