哈希值Perl的求平均值

问题描述 投票:0回答:1

我希望返回下面的平均哈希值(每个键)(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

        }
    }
}

perl hash perl-hash
1个回答
0
投票

使用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;
}
© www.soinside.com 2019 - 2024. All rights reserved.