Traversing a multi-dimensional hash in Perl

后端 未结 8 1972
后悔当初
后悔当初 2021-01-03 04:02

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 hav

8条回答
  •  佛祖请我去吃肉
    2021-01-03 04:15

    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.

提交回复
热议问题