如何使用perl split从多行中提取第三列?

时间:2015-07-21 03:59:29

标签: regex perl split

从我尝试使用mapsplit的文件中的多行句子中提取第三列。我得到了很好的结果,我尝试仅使用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 个答案:

答案 0 :(得分:3)

在您的示例中,您将整个数据放入数组并尝试/* * This is used to receive the updated time from broadcast receiver * */ private final BroadcastReceiver timeBroadCaster = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //method used to update your GUI fields updateGUI(intent); } }; /** * update IU with changing timer of Focus Hour * * @param intent Focus hour timer value */ private void updateGUI(Intent intent) { AppLog.showLog("Update UI", "Timer Stopped"); if (intent.getExtras() != null) { String focusHMS = intent.getStringExtra(Constants.HOCUS_FOCUS_TIMER); focusMilliSecond = intent.getLongExtra(Constants.HOCUS_FOCUS_TIMER_MILLI_SECOND, 0); txtFocusHourTimer.setText("" + focusHMS); } } @Override public void onResume() { super.onResume(); registerReceiver(timeBroadCaster, new IntentFilter( HokusFocusCountDownTimer.COUNTDOWN_BROADCAST_RECEIVER)); } @Override public void onPause() { super.onPause(); try { unregisterReceiver(timeBroadCaster); } catch (Exception e) { e.printStackTrace(); } } ,即您将split $m[3]称为数组,其中$m是标量。当您使用$muse strict时, 然后你会得到错误:

use 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>);

答案 1 :(得分:0)

这是用于提取列的Perl one liner(注意:这仅适用于空白分隔文件):

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

输出:

9.00am
10.00am
11.00am
12.00am
13.00pm

请参阅perlrun以了解Perl解释器的执行情况。