An Array of Hashes (1) is similar to an Array of Arrays. The initialization of an array of hashes consists of an array
variable (@AoH) to which a list is assigned. This list includes references to hashes separated by the curly brackets and separated by commas.
Within the hashes the individual key/value pairs are defined. Recall that members of %name_hash are accessed by $name_hash{$key}
Recall how to construct an anonymous hash reference with curly braces {}:
$anon_hash_ref = {'key1' => 'value1', 'key2' => 'value2'};
Alternatively, you could use the following code for the construction of an AoH, but it is less clear.@AoH = ( # array of hashes; notice the open and close parenthesis: it's a real array!
{
'name' => 'Sebastian',
'age' => 40,
},
{
'name' => 'Daniel',
'age' => 38,
},
{
'name' => 'Florence',
'age' => 36,
}
);
See also below.@AoH = (
{ qw (name Sebastian age 40), },
{ qw (name Daniel age 38) },
{ qw (name Florence age 36) },
);
$AoH[0]{children}=2;
$AoH[2]{children}=3;
@AoH_copy = @AoH;
@AoH_combi = (@AoH1, @AoH2);
@AoH_copy = ();
$AoH[0]->{name}; # output: Sebastian
The age of 'Florence' is: $AoH[2]->{age};# output: 36
$AoH_length = scalar (@AoH);
$index_last_element = $AoH_length - 1;
The key order of hashes when printing the complete AoH seems to be random, also in case of the Array of Hashes. You've to use some sort mechanism in order to get expected results. In addition, sorting on a key would be nice. The following code -without for loops but with 'map'- is your friend!print "AoH: $AoH[0]->{name}\n"; # output: Sebastian
print "AoH: $AoH[0]{name}\n";# you may omit the arrow; output: Sebastian
Each element of the array is passed to the special variable '$_' when using 'map'!@AoH_sorted = sort { $a->{age} <=> $b->{age} } @AoH; # sorting on 'age'; read Chapter 1.6 Sort of Part 2
print join "\n", map {"Name: " . $_->{name}."\nAge: " . $_->{age} . "\n"} @AoH_sorted;
@AoH_copy = @AoH;foreach (@AoH_copy) { print "[ name: $_->{name} age: $_->{age} ]\n";}
which is equivalent topush (@AoH , {'name' => 'Kirsten', 'age' => 42});
and topush (@AoH,{'name','Kirsten','age', 42});
Building the Array of Hashes, while reading formatted data from a text file, you could think of the following:push (@AoH, { qw(name Kirsten age 42) } );
$input_str = "name=Kirsten age=42";
@member = split (/[\s=]+/, $input_str);
push (@AoH_copy,{ @member });
To delete an array by key, use 'grep':delete (@AoH[2]) if (exists @AoH[2]);
@AoH = grep { $_->{'name'} ne 'Daniel' } @AoH;
@AoH = grep { $_->{'age'} != 42 } @AoH;
$AoH[0]->{name} = "SEBASTIAN";