Perl logo

Perl Refreshments ⌘

Hashes #2 - Data Structures

Like arrays of arrays, we can have hashes of hashes (or hashes of arrays), since a hash, like an array, is a collection of scalar quantities.

If you are familiar with data structures, you may know about one called a record. A hash of hashes is like that - it is a record that itself contains other records.

Time for another example ...

my %HoH = (
    flintstones => {
        husband => "fred",
        pal     => "barney",
    },
    jetsons     => {
        husband     => "george",
        wife        => "jane",
        "his boy"   => "elroy", # quotes needed for spaces in key
    },
    simpsons    => {
        husband => "homer",
        wife    => "marge",
        kid     => "bart",
    },
);

To access various pieces of this record, the keys are used as the index to the values, similar to accessing an array.

for my $family (keys %HoH) {
    print "$family:\n";
    for my $role (keys %{ $HoH{$family} } ) {
        print "\t$role --> $HoH{$family}{$role}\n";
    }
    print "\n";
}

Again, note the hash is not sorted, but we can fix that.

for my $family (sort keys %HoH) {
    print "$family:\n";
    for my $role (sort keys %{ $HoH{$family} } ) {
        print "\t$role --> $HoH{$family}{$role}\n";
    }
    print "\n";
}

Note we are only sorting keys in this example.

Accessing individual values is straight-forward, since the index is the key. Here we are looking for the wife's name in the jetsons family:

print "$HoH{jetsons}{husband}'s wife is $HoH{jetsons}{wife}\n";

The syntax is similar to accessing an array, with one difference being the use of braces { } instead of brackets [ ].

Another example with some of my music ...


-30-