perl - 查找哈希值的平均值 Perl
问题描述
我希望返回下面的哈希值(每个键)的平均值(grades.txt)
Melotti, Suzanne: 100 100 95 95 92 87
Wayne, Bruce: 85 85 85 75 75 75
Stark, Tony: 92 92 75 79 91 87
Odinson, Thor: 23 12 10 42 50 64
Kane, Kathy: 100 100 100 100 95 95
Rogers, Steven: 92 91 91 90 87 84
Murdock, Matthew: 100 100 100 99 99 98
VonDoom, Victor: 75 75 72 73 74 80
Queen, Olvider: 92 83 74 65 100 66
Hall, Carter: 23 12 10 42 50 64
Xavier, Charles: 100 100 95 95 92 87
到目前为止,我的子程序看起来像这样:
$grade_file = "grades.txt";
open FILE, "<", $grade_file;
sub avg {
while (<$FILE>){
foreach $line ($grade_file){
# some code
return $total
}
}
}
解决方案
sum
从List::Util使用。要获取元素的数量,只需在标量上下文中使用数组。
#!/usr/bin/perl
use strict;
use warnings;
use feature qw{ say };
use List::Util qw{ sum };
while (<>) {
my ($name, $points) = split /: /;
my @points = split ' ', $points;
say $name, ': ', sum(@points) / @points;
}
推荐阅读
- python - 如何修复settings.py中的collectstatic路径错误
- sql-server - 具有相同顺序的 Azure SQL 查询返回不同的结果集
- javascript - 错误:购物车(...):渲染没有返回任何内容
- snowflake-cloud-data-platform - 从列表雪花访问元素
- c# - WINUI 3.0 - Reunion 0.5 窗口大小///
- java - 地图中值的类型转换
- sql - 在 oracle 中创建用户时出现权限不足错误。如何解决
- fonts - 导入本地字体 Lazarus IDE
- javascript - 抛出新的 Mongoose 错误(''uri'' 参数应该是“openuri”)
- sql-server - SQL Server 用尽内部资源生成查询计划