Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: quick question about hash element access

by tilly (Archbishop)
on Jun 27, 2003 at 21:18 UTC ( [id://269745]=note: print w/replies, xml ) Need Help??


in reply to quick question about hash element access

Sorry, basically you have to do it recursively or using eval. For a miniscule efficiency gain you can use tail-optimization to turn the recursion into iteration like so:
sub nested_lookup { my $node = shift; while (ref($node) and @_) { $node = $node->{ shift(@_) }; } return @_ ? undef : $node; }
and you would call it like this:
my $elem = nested_lookup(\%hash, split /\./, 'a.b.c.d');
(Note: could benefit from more error checking.)

Replies are listed 'Best First'.
Re: Re: quick question about hash element access
by Chmrr (Vicar) on Jun 28, 2003 at 01:11 UTC

    And with very few changes you can make it an lvalue, so you can use it to assign to:

    sub nested : lvalue { @_ == 1 ? $_[0] : nested($_[0]{$_[1]}, @_[2..$#_]); }

    ..and now you can say:

    nested(\%hash, a => b => c =>) = "VALUE";

    TThis can lead to such fun looking constructs as nested $hashref, a => b => c => d => = 42; Note that this code will only work under perl 5.6.0 or later, though; earlier perls had more restricted definitions of lvalues. See also descending a tree of hash references.

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2024-03-29 15:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found