下面我用来$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";
Run Code Online (Sandbox Code Playgroud)
是的,您可以grep
对哈希值运行过滤器来快速计算。
$num_cheap_items = grep { $_ < 4 } values %prices;
@the_cheap_items = grep { $prices{$_} < 4 } keys %prices;
Run Code Online (Sandbox Code Playgroud)