http://www.perlmonks.org?node_id=977996


in reply to (another) HoH question

Because you can assign only one scalar value to a hash slot. So you can say $hash{tree} = 4; or you can say $hash{tree} = {apple => 6}; 1, but not both at the same time.

1: This which would assign a scalar to $hash{tree}, that scalar being a reference to the anonymous hash {apple=>6}. In a way this boils down to the same as $hash->{tree}->{apple} $hash{tree}->{apple} (Update: typo kindly pointed out by AnomalousMonk), see for yourself:

use strict; use warnings; use Data::Dump 'pp'; my %hash; $hash{tree}->{apple} = 6; pp \%hash; $hash{tree} = {apple => 6}; pp \%hash; __END__ { tree => { apple => 6 } } { tree => { apple => 6 } }

If you really need a tree structure, perhaps a hash of arrays would be better suited. It'd get something like this:

use strict; use warnings; use Data::Dump 'pp'; my %hash; $hash{tree} = [4]; push @{$hash{tree}}, {apple => [6]}; pp \%hash; my $apple_tree = $hash{tree}->[1]->{apple}; push @$apple_tree, {red => 9, fuju => 4}; pp \%hash; __END__ { tree => [4, { apple => [6] }] } { tree => [4, { apple => [6, { fuju => 4, red => 9 }] }] }

Or, if you really want your own code to walk over this tree:

for my $key (keys %hash) { my ($root_value, $subtree) = @{$hash{$key}}; print "$key $root_value\n"; for my $subtree_key (keys %$subtree) { my ($subtree_root_value, $subtree_subtree) = @{$subtree->{$sub +tree_key}}; print "$key $subtree_key $subtree_root_value\n"; for my $bottom_level_key (keys %$subtree_subtree) { print "$key $subtree_key $bottom_level_key ", $subtree_ +subtree->{$bottom_level_key}, "\n"; } } } __END__ tree 4 tree apple 6 tree apple fuju 4 tree apple red 9
But as you can see that becomes pretty messy rather quickly, codewise. Perhaps you should reconsider the data structure you want to use?