Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Recursive hash assignment

by Anonymous Monk
on Sep 07, 2002 at 00:37 UTC ( [id://195811]=note: print w/replies, xml ) Need Help??


in reply to Recursive hash assignment

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://195811]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (4)
As of 2024-04-25 14:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found