2015-07-21 76 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解释器。