這是How do I average column values from a tab-separated data file, ignoring a header row and the left column?的後續行動。任務是:打開並閱讀文件;到達每一行,將內容分割成數組,並計算數值的平均值;最後將新的文件寫入每個包含數值的列的平均值。爲什麼我在輸出文件中看不到計算結果?
所有似乎都很好,直到最後一點。問題是,儘管我可以創建一個新的文件,但.txt
文件本身沒有在輸出中打印的內容。最好,作爲Perl的新用戶,我寧願將腳本保留在下面寫的樣式中,以便更好地理解它。我可能不太適合那些更簡潔的版本,可能會在那裏。感謝jchips12是相當有幫助的。
不管怎樣,代碼:從文件Lab1_table.txt
#!/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 $outfile = "Lab1_tableoutput.txt";
open OUTFILE, ">$outfile" or die "Cannot open $outfile: $!";
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";
}
print OUTFILE "\n";
close OUTFILE;
的數據來如下:
retrovirus genome gag pol env
HIV-1 9181 1503 3006 2571
FIV 9474 1353 2993 2571
KoRV 8431 1566 3384 1980
GaLV 8088 1563 3498 2058
PERV 8072 1560 3621 1532
結果產生正確的平均值,雖然有點雜亂在終端和它們沒有被標記爲對應於任何列號/名稱。此外,還生成了一個.txt
文件,但沒有輸出。
結果出來爲:
Argument "" isn't numeric in addition (+) at line 25, <INFILE> line X
0
8649.2
1509
3300.4
2142.4
***Line X: Where X is either 2, 3, 4, 5, or 6.***
從這我可以推斷「參數」的錯誤是指5個標題列,並且0
與非數值的唯一列。
幫助獲取文件寫入.txt
文件,或者在某種程度上我可以讀取命令行中顯示的輸出將不勝感激。另外,雖然我隱約知道代碼的每一步發生了什麼,但如果可能的話,我希望能夠更深入地瞭解大多數步驟中正在發生的事情。我仍然在讀它,但我希望能夠更清楚地理解更多細節。每行
看到我下面的評論。我認爲你可以通過使用模式來修復它:\ t +而不是\ t – 2012-03-16 02:18:27
@PkC:看起來,網站管理員已取消我們上次的討論。如果您發現此評論,則完成的腳本位於[http://derivations.org/acgt.txt]。我的電子郵件(我將很快從這裏刪除)是gmail dot com的tbtkorg。 – thb 2012-03-18 05:21:34