How do I average column values from a tab-separated data file, ignoring a header row and the left column?

不羁的心 提交于 2019-11-29 15:18:54

Here are the points you need to change
Use another variable for the headers

my $count = 0;
my @header = ();
my @average = ();

then change the logic inside if statement

if ( $count == 1 ) {
    @header = @columns;
}

Now don't use the @average for the limit, use $i < scalar @columns for else statement. Initially @average is zero, you will never get inside the for loop ever.

else {
    for( my $i = 1; $i < scalar @columns; $i++ )  {
        $average[$i] += $columns[$i];
    }
}

Finally add -1 to your counter. Remember you increment your counter when you parse your header

for( my $i = 1; $i < scalar @average; $i++ ) {
    print $average[$i]/($count-1), "\n";
}

Here is the final code
You can take advantage of @header to display the result neatly

#!/usr/bin/perl -w

use strict;

my $infile = "Lab1_table.txt"; # This is the file path
open INFILE, $infile or die "Can't open $infile: $!"; 

my $count = 0;
my @header = ();
my @average = ();

while (<INFILE>) {
    chomp;


    my @columns = split /\t/;
    $count++;
    if ( $count == 1 ) {
        @header = @columns;
    }
    else {
        for( my $i = 1; $i < scalar @columns; $i++ )  {
            $average[$i] += $columns[$i];
        }
    }
} 

for( my $i = 1; $i < scalar @average; $i++ ) {
    print $average[$i]/($count-1), "\n";
}

There are other ways to write this code but I thought it would be better to just correct your code so that you can easily understand what is wrong with your code. Hope it helps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!