Bram Vanroy
Bram Vanroy

Reputation: 28427

Read lines from file, calculate average, write average to same file in Perl

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.

Upvotes: 0

Views: 606

Answers (3)

Dave Cross
Dave Cross

Reputation: 69224

You should always add use strict and use warnings to the top of any Perl program that you write. They will help you find bugs.

In this case you would have seen the error:

Filehandle $overviewhandle opened only for output

Which, in my opinion, makes the problem pretty obvious.

Upvotes: 4

Vorsprung
Vorsprung

Reputation: 34297

The open mode of the file is wrong. You need to have it in read/write mode, not append mode

open(my $overviewhandle, '+<','overview.txt');
chomp( my @durations = <$overviewhandle> );
my $avgtime = 0;
foreach my $duration (@durations) {
    $avgtime += $duration;
}
$avgtime = $avgtime / scalar @durations;
print $overviewhandle "================\nAVERAGE after $amountofloops runs: $avgtime";
close $overviewhandle;

Upvotes: 3

fugu
fugu

Reputation: 6568

open my $in, '<', 'in.txt' or die $!;

my $count = 0;
my $total;
while(<$in>){
    $count++;
    $total += $_;
}

open my $out, '>>', 'in.txt' or die $!;

my $average = $total/$count;
print $out "\n================\n";
print $out "AVERAGE after $count runs: $average\n";

Upvotes: 0

Related Questions