如何获取散列中值小于 n 的条目数?

How to get number of entries in a hash with values less than n?

下面我使用 $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";

是的,你可以遍历散列的 keys 并检查每个值是否小于 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

是的,您可以运行对散列值进行grep过滤以快速计算。

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