7. Complex data structures - 4: Hashes of Hashes

A Hash of Hashes (1) is a Hash, where the keys are strings and the values references to anonymous hashes. You can declare a Hash Of Arrays as %HoH. 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'};


7.1 Create

%HoH = ( # hash of hashes; notice the open and close parenthesis: it's a real hash!<
'hash1' => {
'key1' => '1-111',
'key2' => '1-222',
},
'hash2' => {
'key1' => '2-111',
'key2' => '2-222',
},
);
An easier alternative:
%hash1 = ();
$hash1{'key1'} = '1-111';
$hash1{'key2'} = '1-222';

%hash2 = ();
$hash2{'key1'} = '2-111';
$hash2{'key2'} = '2-222';

%HoH = ( 'hash1' => \%hash1, 'hash2' => \%hash2 );
You can extend the existing hashes by new key/value pairs:
$hash1{'key3'} = '1-333';
$hash2{'key3'} = '2-333';
7.1.1 Copy
%HoH_copy = %HoH;
7.1.2 Merge
%HoH_combi = (%HoH1, %HoH2);
7.1.3 Empty
%HoH_copy = ();


7.2 Access

7.2.1 Access members
%HoH_copy = %HoH;
print("{'hash1'}{'key2'}"); # output: 1-222

7.3 Print

Printing keys:
%HoH_copy = %HoH;
foreach (sort(keys(%HoH_copy))) {
print("$_ "); # output: hash1 hash2
}
Printing keys and values:
%HoA_copy = %HoA;
foreach $hash (sort(keys(%HoH_copy))) {

foreach $key (sort(keys %{$HoH_copy{$hash}})) {
print("hash - $key: $HoH_copy{$hash}{$key}\n");
}

}
The output is:
hash1 - key1: 1-111
hash1 - key2: 1-222
hash2 - key1: 2-111
hash2 - key2: 2-222


7.4 Iterate

See 8.3 Print


7.5 Operate

7.5.1 Add an element
$HoH{'hash1'}{'key3'} = '1-333';
7.5.2 Remove an element with 'delete'
The 'Delete' function can be applied in removing an existing hash.
%HoH_copy = %HoH;
delete($HoH_copy{'hash2'}{'key2'}) if (exists $HoH_copy{'hash2'}{'key2'});
7.5.3 Update an element
%HoH_copy = %HoH;
$HoH_copy{'hash1'}{'key1'} = '4-444'


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