in reply to Re: quick question about hash element access
in thread quick question about hash element access

added to your code so it can take a variable length identifier, and accept the hashref.
my %test_hash; $test_hash{'a'}{'b'}{'c'}{'d'} = "Yay"; print get_id(\%test_hash, "a.b.c.d"), "\n"; sub get_id { my $thingy = shift; my @keys = split /\./, shift; foreach my $key ( @keys ) { $thingy = $$thingy{$key}; } return $thingy; }

Replies are listed 'Best First'.
Re: Re: Re: quick question about hash element access
by Nkuvu (Priest) on Jun 27, 2003 at 21:45 UTC

    Interesting. But I have a question (not being totally fluent in references).

    What exactly does the $thingy = $$thingy{$key} line do? My guess is that it assigns a scalar value referred to by the reference which is contained in $thingy{$key}. But I'm not even sure that sentence makes sense, much less if it's accurate. :)

      you are correct sir-
      we are assigning $thingy to the value of whatever is refered to by $thingy{'a'}, in this case, it's the next hashref. this assignment is just repeated a few times till we're all out of keys.

      what's bad about this is that it assumes the caller will pass in a valid path. i guess error checking will be left up to OP...
      $$thingy{$key} is equal to $thingy->{$key}, so it returns the value corresponding to the key $key in the hash pointed to by the reference $thingy.