6. Complex data structures - 3: Hashes of Arrays

A Hash of Arrays (1) is a Hash, where the keys are strings and the values references to anonymous arrays. You can declare a Hash Of Arrays as %HoA.

Recall to construct an anonymous array reference with square brackets: []

$anon_array_ref = ['scalar_1', 'scalar_2', 'scalar_3'];


6.1 Create

%HoA = ( # hash of arrays; notice the open and close parenthesis: it's a real hash!<
'Sebastian' => ['red', 'blue'],
'Daniel' => ['brown', 'green'],
'Florence'=> ['blue', 'black', 'orange'],
);
You can extend the existing hashes by new key/value pairs:
$HoA{'Kirsten'} = ['green','yellow'];
6.1.1 Copy
%HoA_copy = %HoA;
6.1.2 Merge
%HoA_combi = (%HoA1, %HoA2);
6.1.3 Empty
%HoA_copy = ();


6.2 Access

6.2.1 Access hash members
@color = @{$HoA{'Kirsten'}};
print("@color\n"); # output: green yellow
print("$color[1]\n"); # output: yellow

6.3 Print

Printing keys:
%HoA_copy = %HoA;
foreach (sort(keys(%HoA_copy))) {
print "$_ "; # output: Daniel Florence Kirsten Sebastian
}
Printing values:
%HoA_copy = %HoA;
foreach (sort(values(%HoA_copy))) {
print "@$_ ";
}
Printing keys and values:
%HoA_copy = %HoA;
foreach $name (sort(keys(%HoA_copy))) {
foreach $color (sort(@{$HoA_copy{$name}})) {
print "$name $color\n";
}
}
The output is:
Daniel brown
Daniel green
Florence black
Florence blue
Florence orange
Kirsten green
Kirsten yellow
Sebastian blue
Sebastian red


6.4 Iterate

See 7.3 Print


6.5 Operate

6.5.1 Add an element
$HoA{'Bibian'} = ['red', 'green','blue'];
Alternatively, you could do the following:
@mc_array = qw(green blue black);
$HoA{'Bibian'} = \@mc_array;
To extend an existing array, you could use the push command.
push(@{$HoA{'Sebastian'}},'black');
6.5.2 Remove an elementn with 'delete'
The 'Delete' function can be applied in removing an existing hash.
delete($HoA{'Sebastian'}) if (exists $HoA{'Sebastian'});
6.5.3 Update an element
$HoA{'Sebastian'} = ['pink', 'yellow', 'purple'];


Footnotes
(1) The common expression Hashes of Arrays is not correct! You should speak of Hashes of References of Arrays.