2010-08-26 29 views
0

我有一些數據從UNIX命令行調用如何在Perl中提取特定數據列?

1 ab 45 1234 
2 abc 5 
4 yy 999 2 
3 987 11 

我會用system()函數調用。

如何在Perl中將第二列數據提取到數組中?此外,數組大小必須取決於我擁有的行數(它不一定是4)。我想讓這個數組有("ab", "abc", "yy", 987)

回答

8
use strict; 
use warnings; 

my $data = "1 ab 45 1234 
2 abc 5 
2 abc 5 
2 abc 5 
4 yy 999 2 
3 987 11"; 

my @second_col = map { (split)[1] } split /\n/, $data; 

要獲得唯一值,請參見perlfaq4。下面是提供有部分的答案:到UNIX腳本:

my %seen; 
my @unique = grep { ! $seen{ $_ }++ } @second_col; 
+0

@FM:什麼'my'嗎? – Lazer 2010-08-26 09:22:38

+2

@Lazer它在當前詞法範圍內聲明變量。你提出的這個問題表明你沒有在你的Perl腳本中啓用'use strict'和可能的'use warnings'。如果沒有,你應該開始這樣做。 – FMc 2010-08-26 09:26:20

+0

@FM:謝謝!雖然這解決了我眼前的問題,是否有一種簡單的方法可以在'second_col'中獲得唯一的結果? – Lazer 2010-08-26 09:29:00

4

你可以連續使用一個Perl CMD線電話(one-liner又名):

perl -lane 'print $F[1]' data.dat 

代替data.dat文件,使用管道從您的命令行工具

cat data.dat | perl -lane 'print $F[1]' 

附錄

擴展爲結果列的唯一岬很簡單:

cat data.dat | perl -lane 'print $F[1] unless $seen{$F[1]}++' 

,或者,如果你很懶(僱用%_):

cat data.dat | perl -lane 'print unless $_{$_=$F[1]}++' 
+0

+1提醒我關於'-a'選項。 – FMc 2010-08-26 09:41:34

+0

好的答案,一定很好,明確指出'-a'選項autosplits爲'@ F'。不知道'-l'做了什麼,但... – 2010-08-26 10:42:19

+0

@PP,-l做適當的*新行*處理,請參閱:http://sial.org/howto/perl/one-liner/,好吧,我加了一個解釋的鏈接(謝謝) – 2010-08-26 10:48:23