Perl:平均文件中的数字

时间:2015-10-25 08:59:16

标签: perl

我有一个文件,其中每一行都包含一个数值:

1
2
3
3
1

我的功能看起来像这样:

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);

但是我在$count ++=;行收到错误,说明&#34; + =;&#34;附近有语法错误。

3 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

增加=后无需$count++。你可以这么简单地做到这一点:

#!/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

执行程序为:

./scriptname file.txt

输出:

Average = 2

答案 2 :(得分:-1)

您问题的理想代码如下所示:

#!/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);