如何获取哈希表中值小于n的条目数量?

7

以下我使用$size = keys %prices;来获取哈希表中条目的总数。然而,在下面的例子中是否有一种方法可以获取价格低于$4的条目数量?

use strict;

my %prices;

# create the hash
$prices{'pizza'} = 12.00;
$prices{'coke'} = 1.25;
$prices{'sandwich'} = 3.00;
$prices{'pie'} = 6.50;
$prices{'coffee'} = 2.50;
$prices{'churro'} = 2.25;

# get the hash size
my $size = keys %prices;

# print the hash size
print "The hash contains $size elements.\n";
2个回答

9

是的,你可以在哈希值的值上运行 grep 过滤器来快速计算这个值。

 $num_cheap_items = grep { $_ < 4 } values %prices;
 @the_cheap_items = grep { $prices{$_} < 4 } keys %prices;

4

是的,您可以循环遍历哈希表的并检查每个值是否小于4:

my $num = 0;
for (keys %prices) {
    $num++ if $prices{$_} < 4;
}
print "less than 4: $num\n";

输出:

The hash contains 6 elements.
less than 4: 4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接