February 2012
Intermediate to advanced
1184 pages
37h 17m
English
Here are some techniques for populating an array of hashes. To read from a file with the following format:
husband=fred friend=barney
you could use either of the following two loops:
while ( <> ) {
$rec = {};
for $field ( split ) {
($key, $value) = split /=/, $field;
$rec–>{$key} = $value;
}
push @AoH, $rec;
}
while ( <> ) {
push @AoH, { split /[\s=]+/ };
}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 ( @fields = get_next_pair() ) {
push @AoH, { @fields };
}
while (<>) {
push @AoH, { get_next_pair($_) };
}You can append new members to an existing hash like so:
$AoH[0]{pet} = "dino";
$AoH[2]{pet} = "santa’s little helper";Read now
Unlock full access