我正在研究一个取 1 个或多个数组的平均值的子程序。我想在不使用模块的情况下做到这一点。
use strict;
use warnings;
use List::Util 'sum';
my @w = (0, 2);
my @x = (1, 3);
my @y = (2, 2);
my @z = (1, 1);
# the average of these four arrays is (1,2) since
# (0+1+2+1)/4 = 1 and (2+3+2+1)/4 = 2
my @arrays = \(@w, @x, @y, @z);
my @avg;
# this is the way to do it using the module
for my $i (0..$#w) {
$avg[$i] = sum(map $_->[$i], @arrays) / @arrays;
}
print "@avg\n";
# my way of doing it without module
@avg;
for my $i (0..$#w) {
$avg[$i] = prod_sum(map $_->[$i], \@arrays) / @arrays;
}
print "@avg\n";
# subroutines
sub prod_sum{
my $o = $_[0];
my $arr_ref = $_[1];
my $array_ref;
foreach my $row (@$arr_ref){
foreach my $cell (@$row) {
push(@{ $array_ref }, $_);
}
}
my $sum = $o + the_sum($array_ref);
return $sum;
}
sub the_sum{
my $sum = 0;
for ( @{$_[0]} ) {
$sum += $_;
}
return $sum;
}
输出
1 2
[pair of really random big numbers]
第一个输出是正确的。它显示所有数组的平均值。第二个输出是完全错误的。如何在不使用模块的情况下做到这一点?