1 1ddd2d4e 2023-09-10 jrmu #!/usr/bin/perl
3 1ddd2d4e 2023-09-10 jrmu # Modify the program from Exercise 1 to use JSON instead of Storable.
6 1ddd2d4e 2023-09-10 jrmu use warnings;
9 1ddd2d4e 2023-09-10 jrmu use Data::Dumper;
10 1ddd2d4e 2023-09-10 jrmu use local::lib;
14 1ddd2d4e 2023-09-10 jrmu my $storagepath = "ex6-2.data";
15 1ddd2d4e 2023-09-10 jrmu if (-e $storagepath) {
17 1ddd2d4e 2023-09-10 jrmu open my $fh, '<', $storagepath or die "Unable to read from '$storagepath': $!";
18 1ddd2d4e 2023-09-10 jrmu my $data = <$fh>;
19 1ddd2d4e 2023-09-10 jrmu %hosts = %{from_json($data)};
21 1ddd2d4e 2023-09-10 jrmu while (<>) {
22 1ddd2d4e 2023-09-10 jrmu next if (/\A\s*#/);
23 1ddd2d4e 2023-09-10 jrmu my ($src, $dst, $bytes) = split;
24 1ddd2d4e 2023-09-10 jrmu $hosts{$src}{$dst} += $bytes;
26 1ddd2d4e 2023-09-10 jrmu open my $fh, '>', $storagepath or die "Unable to write to '$storagepath': $!";
27 1ddd2d4e 2023-09-10 jrmu print $fh to_json(\%hosts, { pretty => 1 });
29 1ddd2d4e 2023-09-10 jrmu my $hashref = shift;
31 1ddd2d4e 2023-09-10 jrmu foreach (keys %{$hashref}) {
32 1ddd2d4e 2023-09-10 jrmu $total += $hashref->{$_};
34 1ddd2d4e 2023-09-10 jrmu return $total;
36 1ddd2d4e 2023-09-10 jrmu foreach my $src (sort { sum($hosts{$b}) <=> sum($hosts{$a}) } keys %hosts) {
37 1ddd2d4e 2023-09-10 jrmu print "Total bytes ($src): ". sum($hosts{$src}) ."\n";
38 1ddd2d4e 2023-09-10 jrmu foreach my $dst (sort { $hosts{$src}{$b} <=> $hosts{$src}{$a} }
39 1ddd2d4e 2023-09-10 jrmu keys %{$hosts{$src}}) {
40 1ddd2d4e 2023-09-10 jrmu print "$src => $dst $hosts{$src}{$dst}\n";