I have Hash where values of keys are other Hashes.
Example: {'key' => {'key2' => {'key3' => 'value'}}}
How can I iterate through this structure?
I have Hash where values of keys are other Hashes.
Example: {'key' => {'key2' => {'key3' => 'value'}}}
How can I iterate through this structure?
This answer builds on the idea behind Dave Hinton's -- namely, to write a general purpose subroutine to walk a hash structure. Such a hash walker takes a code reference and simply calls that code for each leaf node in the hash.
With such an approach, the same hash walker can be used to do many things, depending on which callback we give it. For even more flexibility, you would need to pass two callbacks -- one to invoke when the value is a hash reference and the other to invoke when it is an ordinary scalar value. Strategies like this are explored in greater depth in Marc Jason Dominus' excellent book, Higher Order Perl.
The earlier answers show how to roll your own solution, which is good to do at least once so you understand the guts of how perl references and data structures work. You should definitely take a read through perldoc perldsc and perldoc perlref if you haven't already.
However, you don't need to write your own solution -- there is already a module on CPAN which will iterate through arbitrarily-complex data structures for you: Data::Visitor.
You will have to loop through it twice. i.e.
If you are using perl as a "CPAN interpreter" then in addition to
Data::Visitor
andData::Deep
there is the super simpleData::Traverse
:Output:
$a
and$b
are treated as special variables here (as withsort()
) while inside thetraverse()
function.Data::Traverse
is a very simple but immensely useful module with no non-CORE dependencies.Also, please read through perldoc perldsc. You can learn about hashes in depth