Traversing a multi-dimensional hash in Perl

后端 未结 8 1982
后悔当初
后悔当初 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:17

    Here's an option. This works for arbitrarily deep hashes:

    sub deep_keys_foreach
    {
        my ($hashref, $code, $args) = @_;
    
        while (my ($k, $v) = each(%$hashref)) {
            my @newargs = defined($args) ? @$args : ();
            push(@newargs, $k);
            if (ref($v) eq 'HASH') {
                deep_keys_foreach($v, $code, \@newargs);
            }
            else {
                $code->(@newargs);
            }
        }
    }
    
    deep_keys_foreach($f, sub {
        my ($k1, $k2) = @_;
        print "inside deep_keys, k1=$k1, k2=$k2\n";
    });
    

提交回复
热议问题