hash_of_hash.pl (2370B) - raw
1 #!/usr/local/bin/perl 2 3 # 4 # this program demonstrates hash autovivification as described in 5 # Chatper 5, "References and Scoping" of "Intermediate Perl, 2nd Edition" 6 # https://www.oreilly.com/library/view/learning-perl-objects/0596004788/ch04.html 7 # 8 # it also experiements with some ways to print complex data structures using 9 # various modules such as Data::Dumper, JSON and YAML. 10 # 11 12 use strict; 13 use warnings; 14 use v5.22; 15 use Data::Dumper; 16 use Data::Dump qw(dump); 17 use Data::Printer; 18 use YAML; 19 use JSON; 20 21 my %total_bytes; 22 23 die "Usage: $0 [filename]" if (@ARGV != 1); 24 my $filename = shift; 25 open my $fh, '<', $filename 26 or die "Could not open file $filename: $!"; 27 28 while (<$fh>) { 29 my ($source, $destination, $bytes) = split; 30 $total_bytes{$source}{$destination} += $bytes; 31 #print Dumper( \%total_bytes ); 32 } 33 34 my @column_width = (23, 23, 16); 35 my $format = "%-23s %-23s %16d\n"; 36 #my $format = sprintf "%-*s %-*s %*d\n", foreach @column_width; 37 say "===========START OF REPORT=============="; 38 printf "%-23s %-23s %-16s\n", "Source", "Destination", "Bytes Transfered"; 39 printf "%-23s %-23s %-16s\n", "-"x23, "-"x23, "-"x16; 40 for my $source (sort keys %total_bytes) { 41 for my $destination (sort keys %{ $total_bytes{$source} }) { 42 printf $format, $source, $destination, 43 $total_bytes{$source}{$destination}; 44 } 45 } 46 say "===========START of DUMPER==============="; 47 print Dumper( \%total_bytes ); # this one is the best 48 #say "+++++++++++++++++++++++++++++++"; 49 #dump( \%total_bytes); 50 #say "+++++++++++++++++++++++++++++++"; 51 #p( %total_bytes); 52 #say "===========START of DUMP================="; 53 #print Dump( \%total_bytes ); 54 #say "+++++++++++++++++++++++++++++++"; 55 say "===========START of JSON================="; 56 print to_json( \%total_bytes, { pretty => 1 } ); # not bad 57 say "===========END of JSON==================="; 58 my $json_in = to_json( \%total_bytes, { pretty => 1 } ); 59 say "--------should be same as before-----------"; 60 say $json_in; 61 $json_in = "[\n".$json_in."]"; 62 say "----------not sure what this is-------------"; 63 say $json_in; 64 my $hash_ref = from_json( $json_in ); # this actually an array ref now that 65 # we added the opening and closing brackets above 66 67 #for my $s (sort keys %{$hash_ref}) { 68 # say $s; 69 #} 70 say "============start of final report=========="; 71 foreach (@$hash_ref) { 72 for my $s (keys %{$_}) { 73 say $s; 74 } 75 }