用Perl计算人员分数平均值:无法存储数值求解决方案
问题:计算人员分数平均值的Perl脚本优化
输入文件格式
Person 1 Scores (\ "0.06, 0.01, 0.07, 0.07, 0.75", \ "0.05, 0.08, 0.01, 0.09, 0.08", \ "0.10, 0.10, 0.11, 0.12, 0.10", \ "0.18, 0.19, 0.20, 0.20, 0.19", \ "0.31, 0.32, 0.32, 0.33, 0.32"); } Person 2 Scores (\ "0.06, 0.01, 0.07, 0.07, 0.75", \ "0.05, 0.08, 0.01, 0.09, 0.08", \ "0.10, 0.10, 0.11, 0.12, 0.10", \ "0.18, 0.19, 0.20, 0.20, 0.19", \ "0.31, 0.32, 0.32, 0.33, 0.32"); }
期望输出
Person 1 - (avg value) Person 2 - (avg value)
现有代码问题
你尝试的Perl代码无法正确存储数值到数组进行平均值计算:
open($in, “<file.txt>”) or die; while(<$in>) { if (/Person/) { if (/Scores/../}/) { $_ =~ s/,//g; $_ =~ s/\///g; # removing all unwanted characters to take avg of numbers $_ =~ s/"//g; $_ =~ s/values//g; $_ =~ s/\(//g; $_ =~ s/\)//g; $_ =~ s/;//g; $_ =~ s/}/ /g; @a1 = split(" ",$_); } } }
解决方案
你的代码核心问题包括:
- 未在切换人员时重置统计变量,导致数据混淆
- 嵌套的正则匹配逻辑错误,无法精准捕获每个人员对应的分数块
- 缺失分数累加与平均值计算的逻辑
修正后的代码如下:
use strict; use warnings; my $current_person; my ($total, $count) = (0, 0); open(my $in, '<', 'file.txt') or die "无法打开文件: $!"; while (my $line = <$in>) { chomp $line; # 匹配人员标识行 if ($line =~ /^Person (\d+)$/) { # 输出上一个人员的结果(如果存在) if (defined $current_person) { my $avg = $count ? sprintf("%.4f", $total / $count) : 0; print "$current_person - $avg\n"; # 重置统计变量 ($total, $count) = (0, 0); } $current_person = "Person $1"; } # 提取引号内的分数列表 elsif ($line =~ /"([^"]+)"/) { my @scores = split /,\s*/, $1; foreach my $score (@scores) { $total += $score; $count++; } } } # 处理最后一个人员的结果 if (defined $current_person) { my $avg = $count ? sprintf("%.4f", $total / $count) : 0; print "$current_person - $avg\n"; } close $in;
代码说明
use strict; use warnings;:开启严格语法检查,避免未声明变量等低级错误- 状态管理:用
$current_person跟踪当前处理的人员,$total和$count分别记录分数总和与数量 - 人员切换处理:遇到新的人员行时,先输出上一个人员的平均值,再重置统计状态
- 分数提取:通过正则匹配引号内的内容,按逗号分割得到单个分数,逐个累加统计
- 格式化输出:用
sprintf控制平均值的小数位数(示例保留4位),确保输出整洁
运行该脚本后,将得到符合期望格式的人员平均值结果。
内容的提问来源于stack exchange,提问作者flash
相关产品推荐
相关产品推荐

