I have a file that contains some lines with floating numbers, something like this:
1.66278886795044
1.61858296394348
1.66523003578186
1.62150096893311
1.6725389957428
I am trying to open that file, calculate the average of all lines, and then write the average to the same file. Where 5
stands for the amount of items, the expected output would thus be:
1.66278886795044
1.61858296394348
1.66523003578186
1.62150096893311
1.6725389957428
================
AVERAGE after 5 runs: 1.6481283664703
Considering I can get the amount of runs from a variable higher up in the script $amountofloops
, I thought this would do it:
open(my $overviewhandle, '>>', 'overview.txt');
chomp( my @durations = <$overviewhandle> );
my $avgtime = 0;
foreach my $duration (@durations) {
$avgtime += $duration;
}
$avgtime = $avgtime / $amountofloops;
print $overviewhandle "================\nAVERAGE after $amountofloops runs: $avgtime";
close $overviewhandle;
However, $avgtime
keeps returning zero and I don't know why. I think the number isn't parsed as a number.