如何测试散列的所有值是否等于给定值

时间:2013-08-21 08:45:08

标签: perl

我正在处理像哈希这样的哈希:

my %hash1 = (
  key1 => 0,
  key2 => 1,
  key3 => 0,
);

如果%hash1所有值(不只是一个值)的值为1,我想做点什么。

怎么写呢?

作为参考,我可以写:

for $key ( keys %hash1 ) {
   if ( $hash1{$key} == 1 ){
    #do something
   }
}

这是错误的,因为即使一个键的值等于1,代码的#do something部分也会运行。如果至少有一个键等于1,我写的代码显然会做一些事情。这样的话会很好:

for $key ( keys %hash1 ) {
   if ( exists( $hash1{$key} == 1 ) ){
    #do something
   }
}

3 个答案:

答案 0 :(得分:6)

我会这样做:

my $not_all_ones = grep { $_ != 1 } values %hash1;

答案 1 :(得分:4)

您可以使用List::MoreUtils

use List::MoreUtils qw/all/;

if (all { $_ == 1 } values %hash) {
  # iterate the hash
  while (my ($k, $v) = each %hash) {
    ...
  }
}

all { something($_) } @list是一种奇特的写作方式

!grep { !something($_) } @list

使用De Morgan's Law

请注意,my %hash = { key => 1 }不会创建您想要的数据结构。相反,这会将键"HASH(0x1234567)"映射到undef。如果您use warnings,您将收到一条消息,告诉您正在使用(哈希)引用,其中包含预期列表。使用键值列表初始化哈希:my %hash = ( key => 1)

答案 2 :(得分:2)

if内设置一个标志,并在循环后检查其值。

$all_are_one = $all_are_one && $hash1{$key} == 1

您需要在循环

之前将其设置为true