2017-07-12 47 views
0
chr1 1 10 el1 
chr1 13 20 el2 
chr1 50 55 el3 

我有這個製表符分隔的文件,我想用perl提取第二和第三列。我怎樣才能做到這一點?如何提取perl中的特定列?

我嘗試使用文件處理程序讀取文件並將其存儲在一個字符串,然後將字符串轉換爲數組,但卻沒有得到我到任何地方。

我的嘗試是:

while (defined($line=<FILE_HANDLE>)) { 
    my @tf1; 
    @tf1 = split(/\t/ , $line); 
} 
+0

是,當你在你的腳本編寫它的代碼?它在'while'代碼塊周圍缺少大括號,如果您將「嚴格使用」,則會產生錯誤;在腳本的頂部 –

+0

我的整個代碼超過100行,它包含使用嚴格和使用警告。這僅僅是一個摘錄 – momo12321

+2

的是代碼(與加括號)應該做你想要的東西 - 所以這個問題是最有可能在其他地方。一個[mcve]會告訴我們問題的實際位置 –

回答

1
use strict; 

my $input=shift or die "must provide <input_file> as an argument\n"; 

open(my $in,"<",$input) or die "Cannot open $input for reading: $!"; 

while(<$in>) 
{ 
    my @tf1=split(/\t/,$_); 
    print "$tf1[1]|$tf1[2]\n"; # $tf1[1] is the second column and $tf1[2] is the third column 
} 
close($in) 
4

簡單的自動分割選項卡上的

#          ↓ index starts on 0 
$ perl -F'\t' -lane'print join ",", @F[1,2]' inputfile 

輸出:

1,10 
13,20 
50,55 

perlrun

1

什麼問題,你有?你的代碼已經完成了所有困難的部分。

while (defined($line=<FILE_HANDLE>)) { 
    my @tf1; 
    @tf1 = split(/\t/ , $line); 
} 

您的@tf1陣列中的所有三列(順便說一句 - 你的變量命名需要認真的工作!)所有你現在需要做的是打印從數組的第二和第三個元素(但請記住, Perl數組元素從零開始編號)。

print "$tf1[1]/$tf1[2]\n"; 

利用Perl的默認行爲,可以大大簡化您的代碼。

while (<FILE_HANDLE>) {   # Store record in $_ 
    my @tf1 = split(/\t/);  # Declare and initialise on one line 
           # split() works on $_ by default 
    print "$tf1[1]/$tf1[2]\n"; 
} 
相關問題