Perl grep嵌套哈希递归

时间:2013-10-28 07:50:00

标签: perl hash nested

我的结构看起来像这样(散列哈希):

%hash=(
Level1_1=> {    
 Level2_1 => "val1",
 Level2_2=> { 
  Level3_1 => "val2",
  Level3_2 => "val1",
  Level3_3 => "val3",
 },
Level2_3 => "val3",
},
 Level1_2=> {   
  Level2_1 => "val1",
  Level2_2=> {  
   Level3_1 => "val1",
   Level3_2 => "val2",
   Level3_3 => "val3",
  },
 Level2_3 => "val3",
 },
 Level1_3=> {   
  Level2_1 => "val1",
  Level2_2 => "val2",
  Level2_3 => "val3",
 });

我想grep这个由“val2”过滤的嵌套结构 输出应该是:

%result=(
    Level1_1=> { Level2_2=> { Level3_1 => "val2"} },
    Level1_2=> { Level2_2=> { Level3_2 => "val2" } },
    Level1_3=> { Level2_2 => "val2" }
    );

我的第一个想法是使用这样的递归子程序:

hashwalk_v( \%hash );
sub hashwalk_v
{
    my ($element, @array) = @_;
    if( ref($element) =~ /HASH/ )
    {
   while (my ($key, $value) = each %$element)
   {

     if( ref($value) =~ /HASH/ ) {
      push (@array, $key);
      hashwalk_v($value, @array);
     } else {
      if ( $value =~ "val2") {
       push (@array, $key);
       print $_ .  "\n" for @array;
      } else {
       @array =""; 
      }
     }
   }
 }
}

但遗憾的是我无法保存前一个循环中的哈希密钥。 任何想法??

2 个答案:

答案 0 :(得分:6)

类似的方法,

use Data::Dumper; print Dumper hfilter(\%hash, "val2");

sub hfilter {
  my ($h, $find) = @_;
  return if ref $h ne "HASH";

  my %ret = map {
    my $v = $h->{$_};
    my $new = ref($v) && hfilter($v, $find);

    $new ? ($_ => $new)
      : $v eq $find ? ($_ => $v)
      : ();

  } keys %$h;

  return %ret ? \%ret : ();
}

答案 1 :(得分:5)

递归是正确的答案,但你似乎在路上有点困惑。 :)随时建立新的哈希值,一次一个级别:

sub deep_hash_grep {
    my ($hash, $needle) = @_;

    my $ret = {};
    while (my ($key, $value) = each %{$hash}) {
        if (ref $value eq 'HASH') {
            my $subgrep = deep_hash_grep($value, $needle);
            if (%{$subgrep}) {
                $ret->{$key} = $subgrep;
            }
        }
        elsif ($value =~ $needle) {
            $ret->{$key} = $value;
        }
    }

    return $ret;
}
相关问题