2011-08-18 37 views
1

自定義格式我有一個\t分隔的輸出文件:幫助解析標籤文件,並在Perl

Data for 08/10/2011 
Host QueueName Queue-id  
test 123 Test Q 110 
test 456 Test Q 120 
test 789 Test Q 130 

我期待除去第一行(日期),然後我想二號線(頭列),以 打印出來,象這樣爲我的最終輸出文件中的值:

Host=test QueueName=123 Test Q Queue-id=110 
Host=test QueueName=456 Test Q Queue-id=120 
Host=test QueueName=789 Test Q Queue-id=130 

什麼是一個好辦法/做法在Perl中做到這一點?

回答

2

我會推薦Text::CSV_XS來閱讀文件。

在這最近的問題,有一個類似的問題:How can I use Perl extract a particular column from a tab-separated file?(見我的答案)

use warnings; 
use strict; 
use Text::CSV_XS; 
use autodie; 

my $csv = Text::CSV_XS->new({ sep_char => "\t" }); 
<DATA>; # discard the first line 
$csv->column_names ($csv->getline (*DATA)); 
my $hr = $csv->getline_hr_all(*DATA); 

for my $hashref (@$hr) { 
    my @list; 
    for my $key ($csv->column_names()) { 
     push @list, join '=', $key, $hashref->{$key}; 
    } 
    print "@list\n"; 
} 
__DATA__ 
Data for 08/10/2011 
Host QueueName Queue-id  
test 123 Test Q 110 
test 456 Test Q 120 
test 789 Test Q 130 
+0

感謝您的幫助。我能夠成功地嘗試你指出的另一個例子(使用'getline_hr')。我試過這段代碼,顯然,我錯過了一些東西。 '無法在@ INC中找到auto/Text/CSV_XS/getline_hr_.al。這是否與我的Perl版本有關?再次感謝。 – jdamae

+0

不,如果您可以使用'getline_hr',則可以使用'getline_hr_all'。但是,這個錯誤看起來很麻煩。 '@ INC'是perl找到模塊的地方。這些功能在模塊中。我的猜測是你在你的代碼中犯了一個錯字。 – TLP