You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl如何统计哈希中值小于指定数值n的条目数量

解决方法

你可以通过以下两种常用方式统计价格小于$4的条目数量:

  • 方案1:使用grep直接统计(写法最简洁,适合仅统计数量的场景)
    在标量上下文中调用grep筛选符合条件的哈希值,返回结果就是匹配的条目数:
my $count_under_4 = grep { $_ < 4 } values %prices;
  • 方案2:遍历哈希值累加统计(适合需要额外处理匹配项的场景)
    如果后续还要对符合条件的条目做其他操作,可以用循环遍历计数:
my $count_under_4 = 0;
foreach my $price (values %prices) {
    $count_under_4++ if $price < 4;
}

完整运行示例

use strict;
use warnings; # 建议加上warning提示方便排查问题

my %prices;

# 创建哈希
$prices{'pizza'} = 12.00;
$prices{'coke'} = 1.25;
$prices{'sandwich'} = 3.00;
$prices{'pie'} = 6.50;
$prices{'coffee'} = 2.50;
$prices{'churro'} = 2.25;

# 获取哈希总条目数
my $size = keys %prices;
# 统计价格小于4的条目数
my $count_under_4 = grep { $_ < 4 } values %prices;

# 打印结果
print "哈希共有 $size 个元素。\n";
print "价格小于4的条目共有 $count_under_4 个。\n";

运行后输出结果为:

哈希共有 6 个元素。
价格小于4的条目共有 4 个。

内容的提问来源于stack exchange,提问作者gatorreina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:36:07