#!/usr/local/bin/perl # # this program demonstrates hash autovivification as described in # Chatper 5, "References and Scoping" of "Intermediate Perl, 2nd Edition" # https://www.oreilly.com/library/view/learning-perl-objects/0596004788/ch04.html # # it also experiements with some ways to print complex data structures using # various modules such as Data::Dumper, JSON and YAML. # use strict; use warnings; use v5.22; use Data::Dumper; use Data::Dump qw(dump); use Data::Printer; use YAML; use JSON; my %total_bytes; die "Usage: $0 [filename]" if (@ARGV != 1); my $filename = shift; open my $fh, '<', $filename or die "Could not open file $filename: $!"; while (<$fh>) { my ($source, $destination, $bytes) = split; $total_bytes{$source}{$destination} += $bytes; #print Dumper( \%total_bytes ); } my @column_width = (23, 23, 16); my $format = "%-23s %-23s %16d\n"; #my $format = sprintf "%-*s %-*s %*d\n", foreach @column_width; say "===========START OF REPORT=============="; printf "%-23s %-23s %-16s\n", "Source", "Destination", "Bytes Transfered"; printf "%-23s %-23s %-16s\n", "-"x23, "-"x23, "-"x16; for my $source (sort keys %total_bytes) { for my $destination (sort keys %{ $total_bytes{$source} }) { printf $format, $source, $destination, $total_bytes{$source}{$destination}; } } say "===========START of DUMPER==============="; print Dumper( \%total_bytes ); # this one is the best #say "+++++++++++++++++++++++++++++++"; #dump( \%total_bytes); #say "+++++++++++++++++++++++++++++++"; #p( %total_bytes); #say "===========START of DUMP================="; #print Dump( \%total_bytes ); #say "+++++++++++++++++++++++++++++++"; say "===========START of JSON================="; print to_json( \%total_bytes, { pretty => 1 } ); # not bad say "===========END of JSON==================="; my $json_in = to_json( \%total_bytes, { pretty => 1 } ); say "--------should be same as before-----------"; say $json_in; $json_in = "[\n".$json_in."]"; say "----------not sure what this is-------------"; say $json_in; my $hash_ref = from_json( $json_in ); # this actually an array ref now that # we added the opening and closing brackets above #for my $s (sort keys %{$hash_ref}) { # say $s; #} say "============start of final report=========="; foreach (@$hash_ref) { for my $s (keys %{$_}) { say $s; } }