How to iterate through Hash (of Hashes) in Perl?

后端 未结 9 902
無奈伤痛
無奈伤痛 2020-12-08 03:20

I have Hash where values of keys are other Hashes.

Example: {\'key\' => {\'key2\' => {\'key3\' => \'value\'}}}

How can I iterate throug

9条回答
  •  被撕碎了的回忆
    2020-12-08 03:41

    If you are using perl as a "CPAN interpreter" then in addition to Data::Visitor and Data::Deep there is the super simple Data::Traverse:

    use Data::Traverse qw(traverse);
    
    my %test_hash = (
      q => [qw/1 2 3 4/],
      w => [qw/4 6 5 7/],
      e => ["8"],
      r => { 
             r => "9"  ,
             t => "10" ,
             y => "11" ,
          } ,
    );
    
    traverse { next if /ARRAY/; print "$a => $b\n" if /HASH/ && $b > 8 } \%test_hash;
    

    Output:

    t => 10
    y => 11
    

    $a and $b are treated as special variables here (as with sort()) while inside the traverse() function. Data::Traverse is a very simple but immensely useful module with no non-CORE dependencies.

提交回复
热议问题