Blob


1 #!/usr/bin/perl
3 # The Professor's data file (mentioned earlier in this chapter) is
4 # available as coconet.dat in the Download section of
5 # http://www.intermediateperl.com/. There may be comment lines (beginning
6 # with a #); be sure to skip them. (That is, your program should skip them.
7 # You might find a helpful hint if *you* read them!) Here are the first
8 # data lines in the file:
9 #
10 # (see 5.References.And.Scoping/coconet.dat)
11 #
12 # Modify the code from this chapter so that each source machine's portion
13 # of the output shows the total bytes from that machine. List the source
14 # machines in order from most to least data transferred. Within each group,
15 # list the destination machines in order from most to least data
16 # transferred to that target from the source machine:
17 #
18 # professor.hut => gilligan.hut: 1845
19 # professor.hut => maryann.hut: 90
20 #
21 # The result should be that the machine that sent the most data will be the
22 # first source machine in the list, and the first destination should be the
23 # machine to which it sent the most data. The Professor can use this
24 # printout to reconfigure the network for efficiency.
26 use v5.24;
27 use warnings;
28 use strict;
29 use utf8;
31 my %hosts;
32 while (<>) {
33 next if (/\A\s*#/);
34 my ($src, $dst, $bytes) = split;
35 $hosts{$src}{$dst} = $bytes;
36 }
37 sub sum {
38 my $hashref = shift;
39 my $total;
40 foreach (keys %{$hashref}) {
41 $total += $hashref->{$_};
42 }
43 return $total;
44 }
45 foreach my $src (sort { sum($hosts{$b}) <=> sum($hosts{$a}) } keys %hosts) {
46 print "Total bytes ($src): ". sum($hosts{$src}) ."\n";
47 foreach my $dst (sort { $hosts{$src}{$b} <=> $hosts{$src}{$a} }
48 keys %{$hosts{$src}}) {
49 print "$src => $dst $hosts{$src}{$dst}\n";
50 }
51 }