TAC has asked for the wisdom of the Perl Monks concerning the following question:

Is there a way to traverse nested hashes in search of a particular value without sitting in for loop and looping through the keys?

Edit ar0n 2001-07-13 -- changed title, previously had the ever so descriptive title "Help"

Replies are listed 'Best First'.
Re: Traversing a nested hash
by dragonchild (Archbishop) on Jul 13, 2001 at 21:51 UTC
    So, you're looking for code that doesn't look like:

    # $hash_ref is passed in and defined outside # $key_to_find is what we want to find. # We will return the value of the first $key_to_find sub traverse_funky_hash { my ($hash_ref, $key_to_find) = @_; HASH_LOOP: foreach (sort keys %$hash_ref) { if ($_ eq $key_to_find) { return ($hash_ref->{$_}, 1); } next HASH_LOOP unless ref($hash_ref->{$_} eq 'HASH'); my ($val, $rc) = traverse_funky_hash($hash_ref->{$_}, $key_to_ +find); return ($val, $rc) if $rc; } return (undef, 0); }

    Obviously, that's for an arbitrarily-nested hash of hashes. (And, yes, I know I'm using ref. Sue me. *grins*)

    Somehow, you want to make it so that you don't have to use the foreach over keys, right?

Re: Traversing a nested hash
by suaveant (Parson) on Jul 13, 2001 at 21:49 UTC
    Probably, but a for loop is probably the best way... if you know every value is a hash ref in a hash you could do
    for(values %foo) { ... }
    but then you won't know what your key is... what is wrong with a for? Gives us a small example of what you are looking to do.

                    - Ant