Blame


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