====== Array of Hashes ======
===== Erstellung eines "Array of Hashes" =====
@AoH = (
{
husband => "barney",
wife => "betty",
son => "bamm bamm",
},
{
husband => "george",
wife => "jane",
son => "elroy",
},
{
husband => "homer",
wife => "marge",
son => "bart",
},
);
Hinzufügen eines hash zum array:
push @AoH, { husband => "fred", wife => "wilma", daughter => "pebbles" };
===== Generation eines Array of Hashes =====
Einlesen einer Datei im Format "husband=fred friend=barney" mit einer der folgenden Schleifen:
while ( <> ) {
$rec = {};
for $field ( split ) {
($key, $value) = split /=/, $field;
$rec->{$key} = $value;
}
push @AoH, $rec;
}
while ( <> ) {
push @AoH, { split /[\s=]+/ };
}
Innerhalb einer Subroutine 'get_next_pair', das eine key/value Paar liefert.
while ( @fields = get_next_pair() ) {
push @AoH, { @fields };
}
while (<>) {
push @AoH, { get_next_pair($_) };
}
Anhängen neuer Einträge an ein existierendes hash:
$AoH[0]{pet} = "dino";
$AoH[2]{pet} = "santa's little helper";
===== Adressierung und Ausgabe eines Array of Hashes =====
$AoH[0]{husband} = "fred"; # Setzen eines expliziten key/value Paars
To capitalize the husband of the second array, apply a substitution:
$AoH[1]{husband} =~ s/(\w)/\u$1/;
Ausgabe aller Daten:
for $href ( @AoH ) {
print "{ ";
for $role ( keys %$href ) {
print "$role=$href->{$role} ";
}
print "}\n";
}
# mit indices:
for $i ( 0 .. $#AoH ) {
print "$i is { ";
for $role ( keys %{ $AoH[$i] } ) {
print "$role=$AoH[$i]{$role} ";
}
print "}\n";
}
====== Quellen ======
* O'REILLY - Programming Perl (https://docstore.mik.ua/orelly/perl4/prog/ch09_03.htm)