An array of hashes is useful when you have a bunch of records that you'd like to access sequentially, and each record itself contains key/value pairs. Arrays of hashes are used less frequently than the other structures in this chapter.
You can create an array of anonymous hashes as follows:
To add another hash to the array, you can simply say:@AoH = ( { husband => "barney", wife => "betty", son => "bamm bamm", }, { husband => "george", wife => "jane", son => "elroy", }, { husband => "homer", wife => "marge", son => "bart", }, );
push @AoH, { husband => "fred", wife => "wilma", daughter => "pebbles" };
Here are some techniques for populating an array of hashes. To read from a file with the following format:
you could use either of the following two loops:husband=fred friend=barney
If you have a subroutine get_next_pair that returns key/value pairs, you can use it to stuff @AoH with either of these two loops:while ( <> ) { $rec = {}; for $field ( split ) { ($key, $value) = split /=/, $field; $rec->{$key} = $value; } push @AoH, $rec; } while ( <> ) { push @AoH, { split /[\s=]+/ }; }
You can append new members to an existing hash like so:while ( @fields = get_next_pair() ) { push @AoH, { @fields }; } while (<>) { push @AoH, { get_next_pair($_) }; }
$AoH[0]{pet} = "dino"; $AoH[2]{pet} = "santa's little helper";
You can set a key/value pair of a particular hash as follows:
To capitalize the husband of the second array, apply a substitution:$AoH[0]{husband} = "fred";
You can print all of the data as follows:$AoH[1]{husband} =~ s/(\w)/\u$1/;
and with indices:for $href ( @AoH ) { print "{ "; for $role ( keys %$href ) { print "$role=$href->{$role} "; } print "}\n"; }
for $i ( 0 .. $#AoH ) { print "$i is { "; for $role ( keys %{ $AoH[$i] } ) { print "$role=$AoH[$i]{$role} "; } print "}\n"; }
Copyright © 2002 O'Reilly & Associates. All rights reserved.