Why do I see no computed results in my output file?

后端 未结 1 1932
情话喂你
情话喂你 2021-01-29 03:56

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

1条回答
  •  失恋的感觉
    2021-01-29 04:20

    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, line X 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.

    0 讨论(0)
提交回复
热议问题