Chapter 6. Manipulating Complex Data Structures

Now that we’ve shown the basics of references, we look at additional ways to manipulate complex data. We start by using the debugger to examine complex data structures and then use Data::Dumper to show the data under programmatic control. Next, we’ll show how to store and retrieve complex data easily and quickly using Storable, and finally we’ll wrap up with a review of grep and map and see how they apply to complex data.

Using the Debugger to View Complex Data

The Perl debugger can display complex data easily. For example, we can single-step through one version of the byte-counting program from Chapter 5:

my %total_bytes;
while (<>) {
  my ($source, $destination, $bytes) = split;
  $total_bytes{$source}{$destination} += $bytes;
}
for my $source (sort keys %total_bytes) {
  for my $destination (sort keys %{ $total_bytes{$source} }) {
    print "$source => $destination:",
     " $total_bytes{$source}{$destination} bytes\n";
  }
  print "\n";
}

Here’s the data we’ll use to test it:

professor.hut gilligan.crew.hut 1250
professor.hut lovey.howell.hut 910
thurston.howell.hut lovey.howell.hut 1250
professor.hut lovey.howell.hut 450
ginger.girl.hut professor.hut 1218
ginger.girl.hut maryann.girl.hut 199

We can do this in any number of ways. One of the easiest is to invoke Perl with a −d switch on the command line:

myhost% perl −d bytecounts bytecounts−in Loading DB routines from perl5db.pl version 1.19 Editor support available. Enter h or `h h' ...

Get Intermediate Perl, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.