Here below is a generic way to get the value from arbitrary nestled keys:
sub get_hash_key {
my ($h, @keys) = @_;
my $v = $h;
$v = $v->{$_} foreach @keys;
return $v;
}
But this isn't so useful if we want to change the data. So instead we want to return a reference to the value:
sub get_hash_key_ref {
my ($h, @keys) = @_;
my $r = \$h;
$r = \$$r->{$_} foreach @keys;
return $r;
}
(Please note that we can't just take
&get_hash_key and make the last line
return \$v.)
This technique has several advantages over the other common way (using
||= {}). One is simplicity. In this you do all the logic in one statement and you don't have to make an exception for the last key. Another is that you let perl to the autovivifying for you, so you don't even have to check for bad values. If there is a defined value that isn't a hash references you'll be notified with a (not-so-nice?) error message. This behaviour, I believe, is the most analogous behaviour you can find to doing a hardcoded dereference (overlooking
eval EXPR), but I shouldn't say too much--it always turns out I missed something.
:)
Cheers,
-Anomo