Reputation: 135
I created a function, which generates a random matrix.
sub gen {
my $x = int(rand($_[0]-1)+1);
my $y = int(rand($_[1]-1)+1);
my $matrix = [ map [ map int(rand($_[2]-1)+1), 1..$x ], 1..$y ];
return $matrix;
}
my $array_ref = $gen(5,10,5);
How could i get the average value for each array of matrix? And if possible without regular expressions.
I haven't understand completely openings of references for arrays yet, but this is my attempt. I was trying to get all values and divide it by @_ which get scalar number of elements in array:
sub func{
my $sum;
my @avg;
my $avg;
foreach (@$array_ref) {
$sum += $_;
$avg = $sum/@_;
}
push (@avg, $avg);
}
Upvotes: 2
Views: 670
Reputation: 50657
If by average you want sum divided by number of elements,
use List::Util qw(sum);
for my $r (@$array_ref) {
printf("%.2f\n", sum(@$r)/@$r);
}
without modules,
sub sum {
my $n = 0;
$n += $_ for @_;
return $n;
}
for my $r (@$array_ref) {
printf("%.2f\n", sum(@$r)/@$r);
}
Upvotes: 1