Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traversing a multi-dimensional hash in Perl

If you have a hash (or reference to a hash) in perl with many dimensions and you want to iterate across all values, what's the best way to do it. In other words, if we have $f->{$x}{$y}, I want something like

foreach ($x, $y) (deep_keys %{$f})
{
}

instead of

foreach $x (keys %f) 
    {
    foreach $y (keys %{$f->{$x}) 
    {
    }
}
like image 553
David Nehme Avatar asked Oct 01 '08 23:10

David Nehme


People also ask

How do I traverse a hash in Perl?

Perl allows to Loop over its Hash values. It means the hash is iterative type and one can iterate over its keys and values using 'for' loop and 'while' loop. In Perl, hash data structure is provided by the keys() function similar to the one present in Python programming language.

How do I create an array of hashes in Perl?

To add another hash to an array, we first initialize the array with our data. Then, we use push to push the new hash to the array. The new hash should have all of its data. As shown below, you can see the difference between the two arrays before and after pushing a new hash.

Can a Key have multiple values Perl?

Each key can only have one value.

Can a Perl hash value be an array?

Elements of hash can be anything, including references to array.


1 Answers

Stage one: don't reinvent the wheel :)

A quick search on CPAN throws up the incredibly useful Data::Walk. Define a subroutine to process each node, and you're sorted

use Data::Walk;

my $data = { # some complex hash/array mess };

sub process {
   print "current node $_\n";
}

walk \&process, $data;

And Bob's your uncle. Note that if you want to pass it a hash to walk, you'll need to pass a reference to it (see perldoc perlref), as follows (otherwise it'll try and process your hash keys as well!):

walk \&process, \%hash;

For a more comprehensive solution (but harder to find at first glance in CPAN), use Data::Visitor::Callback or its parent module - this has the advantage of giving you finer control of what you do, and (just for extra street cred) is written using Moose.

like image 113
Penfold Avatar answered Oct 19 '22 05:10

Penfold