2

我需要获取哈希中某个键的所有值。哈希看起来像这样:

$bean = {
     Key1 => {
               Key4 => 4,
               Key5 => 9,
               Key6 => 10,
             },
     Key2 => {
               Key7 => 5,
               Key8 => 9,
             },
};

我只需要值Key4,例如。其余的不是兴趣点。我怎么能得到这些值?Key5Key6

更新:所以我没有%bean我只是将值添加到$bean这样的:

 $bean->{'Key1'}->{'Key4'} = $value;

希望这可以帮助。

4

5 回答 5

7
foreach my $key (keys %{$bean{Key1}})
{
  print $key . " ==> " . $bean{Key1}{$key} . "\n";
}

应该打印:

Key4 ==> 4
Key5 ==> 9
Key6 ==> 10
于 2009-12-03T12:19:15.567 回答
2

如果%bean是散列的散列,$bean{Key1}则是散列引用。要像操作简单哈希一样操作哈希引用,您需要取消引用它,如下所示:

%key1_hash = %{$bean{Key1}};

要访问散列散列中的元素,您可以使用如下语法:

$element = $bean{Key1}{Key4};

所以,这是一个打印键和值的循环$bean{Key1}

print $_, '=>', $bean{Key1}{$_}, "\n" for keys %{$bean{Key1}};

或者,如果您只想要值,而不需要键:

print $_, "\n" for values %{$bean{Key1}};

有关使用复杂数据结构的更多详细信息,请参阅以下 Perl 文档:perlreftutperldscperllol

于 2009-12-03T13:14:29.790 回答
1

另一个解决方案:

for my $sh ( values %Bean ) {
    print "$_ => $sh->{$_}\n" for grep exists $sh->{$_}, qw(Key4 Key5 Key6);
}
于 2009-12-03T13:28:29.587 回答
1

有关使用 Perl 数据结构的大量示例,请参阅Perl Data Structure Cookbook

于 2009-12-03T17:22:31.563 回答
0

做到这一点的一个好方法——假设你发布的是一个例子,而不是一个单独的案例——是递归的。因此,我们有一个函数可以搜索散列以查找我们指定的键,如果它发现其中一个值是对另一个散列的引用,则调用自身。

sub recurse_hash {
  # Arguments are a hash ref and a list of keys to find
  my($hash,@findkeys) = @_;

  # Loop over the keys in the hash
  foreach (sort keys %{$hash}) {

    # Get the value for the current key
    my $value = $hash->{$_};

    # See if the value is a hash reference
    if (ref($value) eq 'HASH') {
      # If it is call this function for that hash
      recurse_hash($value,@findkeys);
    }

    # Don't use an else in case a hash ref value matches our search pattern
    for my $key (@findkeys) {
      if ($key eq $_) {
        print "$_ = $value\n";
      }
    }
  }
}

# Search for Key4, Key5 and Key6 in %Bean
recurse_hash(\%Bean,"Key4","Key5","Key6");

给出这个输出:

Key4 = 4
Key5 = 9
Key6 = 10
于 2009-12-03T13:15:31.800 回答