This is a follow-up to How do I average column values from a tab-separated data file, ignoring a header row and the left column?. The task was: open and read a file; reach each
Specifying comments for each line to give you clear understanding
#!/usr/bin/perl -w
use strict;
use warnings;
my $infile = "Lab1_table.txt"; # input file path
open INFILE, $infile or die "Can't open $infile: $!"; # input file opened
my $outfile = "Lab1_tableoutput.txt"; # output file path
open OUTFILE, ">$outfile" or die "Cannot open $outfile: $!"; # output file opened
my $count = 0; # count variable to check for header row in file
my @header = (); # variable to store headers/column names of file
my @average = (); # variable to store average calculated for each column
while () {
chomp;
my @columns = split /\s+/; # \s stands for [\ \t\r\n\f]
$count++;
if ( $count == 1 ) {
@header = @columns; # executed only once for header
}
else { # else column executed for remaining rows
for( my $i = 1; $i < scalar @columns; $i++ ) { # $i=1 means skip first column
$average[$i] += $columns[$i]; # calcuate average for each row
}
}
}
for( my $i = 1; $i < scalar @average; $i++ ) {
print OUTFILE $average[$i]/($count-1), "\n"; # This will write to output file
}
close OUTFILE;
Use print OUTFILE $average[$i]/($count-1), "\n";
to write to file.
Error Argument "" isn't numeric in addition (+) at line 25,
could be if values in columns which you are adding,by any chance has string in it and not number.Check your input file.
Note: I am not getting above error.Script runs smooth with above data.However if I change one of number to string,I get this error.