2015-07-21 80 views
0

要從文件中的多行句子中提取第三列,我嘗試使用mapsplit。我得到了良好的效果,我試圖只提取採用分體式:如何使用perl split從多行提取第三列?

#!usr/local/bin/perl 
@arr=<DATA>; 
foreach $m (@arr) 
{ 
@res=split(/\s+/,$m[3]); 
print "@res\n"; 
} 

__DATA__ 
the time is 9.00am 
the time is 10.00am 
the time is 11.00am 
the time is 12.00am 
the time is 13.00pm 
+2

另一個'使用嚴格'和'使用警告'的例子會讓你更接近解決方案。 –

回答

3

在你的榜樣,你正在服用的數組中的全部數據,並試圖split $m[3]即你是指$m爲陣,其中$m是標量。當您將使用use strictuse warnings, 那麼你會得到錯誤:

Global symbol "@m" requires explicit package name at data.pl 

這就是爲什麼你沒有得到你的輸出。你應該試試這個:

#!usr/local/bin/perl 
use strict; 
use warnings; 


my @arr=<DATA>; 
foreach my $m (@arr) 
{ 
my @res=split(/\s+/,$m); # $m will contain each line of file split it with one or more spaces 
print "$res[3]\n"; # print the fourth field 
} 

一個較短的版本將是:

print ((split)[3]."\n") while(<DATA>); 

輸出:

9.00am 
10.00am 
11.00am 
12.00am 
13.00pm 
+0

數組索引3指向第4個字段,而不是第3個字段。 – TLP

+0

對,但從OP的角度來看,我猜他想要第四場。第三個領域是'是',這是相當多餘的和無用的 –

0

這裏是Perl的一個班輪提取柱(注:這將工作僅限空白分隔文件):

perl -ane "print qq(@F[3]\n)" filename.txt 

輸出:

9.00am 
10.00am 
11.00am 
12.00am 
13.00pm 

perlrun瞭解執行Perl解釋器。