Blob


1 #!/usr/bin/perl
3 # The program from Exercise 2 in Chapter 5 needs to read the entire data
4 # file each time it runs. However, the Professor has a new router logfile
5 # each day and doesn't want to keep all that data in one giant file that
6 # takes longer and longer to process.
7 #
8 # Fix up that program to keep the running totals in a data file so the
9 # Professor can run it on each day's logs to get the new totals. Use the
10 # Storable module.
12 use v5.24;
13 use warnings;
14 use strict;
15 use utf8;
16 use Storable qw(nstore retrieve);
17 use Data::Dumper;
19 my %hosts;
20 my $storagepath = "ex6-1.data";
21 if (-e $storagepath) {
22 %hosts = %{retrieve $storagepath};
23 }
24 while (<>) {
25 next if (/\A\s*#/);
26 my ($src, $dst, $bytes) = split;
27 $hosts{$src}{$dst} += $bytes;
28 }
29 nstore \%hosts, $storagepath;
30 sub sum {
31 my $hashref = shift;
32 my $total;
33 foreach (keys %{$hashref}) {
34 $total += $hashref->{$_};
35 }
36 return $total;
37 }
38 foreach my $src (sort { sum($hosts{$b}) <=> sum($hosts{$a}) } keys %hosts) {
39 print "Total bytes ($src): ". sum($hosts{$src}) ."\n";
40 foreach my $dst (sort { $hosts{$src}{$b} <=> $hosts{$src}{$a} }
41 keys %{$hosts{$src}}) {
42 print "$src => $dst $hosts{$src}{$dst}\n";
43 }
44 }