Adrian
Adrian

Reputation: 9793

Perl: averaging numbers in a file

I have a file where each line consists of a numerical value:

1
2
3
3
1

My function looks something like this:

print "Enter file name to average \n";
$infile = <>;
open IN, "$infile";
$total = 0;
$count =0;
while (my $line = <>) {
      $total +=$line;
      $count ++=;
}
print "Average = ", $total / $count, "\n";
close(IN);

But I'm getting an error at the $count ++=; line saying that there's a syntax error near "+=;".

Upvotes: 0

Views: 79

Answers (3)

serenesat
serenesat

Reputation: 4709

No need of = after increment $count++. In simple way you can do like this:

#!/usr/bin/perl
use strict;
use warnings;

my $total = 0;
my $count = 0;
while (<>)
{
    $total += $_;
    $count++;
}
print "Average = ", $total/$count, "\n";

_____file.txt_____
1
2
3
3
1

Execute you program as:

./scriptname file.txt

Output:

Average = 2

Upvotes: 0

Arunesh Singh
Arunesh Singh

Reputation: 3535

The ideal code for your problem should look like below:

#!/usr/bin/perl
use strict;
use warnings;
print "Enter file name to average \n";
chomp( my $infile = <> );    #remove new line characters
open my $IN, '<', $infile
  or die "unable to open file: $! \n"; #use 3 arg file open syntax
my $total = 0;
my $count = 0;
while ( my $line = <$IN> ) {## you should use <>  on file handle
    chomp $line;
    next if ($line=~/^\s*$/); #ignore blank lines
    $total += $line;
    $count++;
}

if($count > 0){
   print "Average = ", $total / $count, "\n";
}
else{
    print "Average cannot be calculated Check if file is blank \n";
}
close($IN);

Upvotes: -1

ysth
ysth

Reputation: 98388

Just do $count++, no =.

See http://perldoc.perl.org/perlop.html#Auto-increment-and-Auto-decrement.

Upvotes: 2

Related Questions