2013-04-07 22 views
1

我想在一些文本解析成其下面示出的表:Perl的文本:: CSV ::啜食過程中固定寬度的輸入

Protocol Address   Age (min) Hardware Addr Type Interface 
Internet 10.35.195.1    - 0024.978a.d2d0 ARPA FastEthernet0/0 
Internet 10.35.195.2   73 0002.16a3.9e40 ARPA FastEthernet0/0 
Internet 10.35.195.12   130 0007.0e5b.861a ARPA FastEthernet0/0 
Internet 10.35.195.14   1 000b.cdc9.7d11 ARPA FastEthernet0/0 
Internet 10.35.195.15   3 0021.5a7b.f2af ARPA FastEthernet0/0 
Internet 10.35.195.16   0 000c.2909.2298 ARPA FastEthernet0/0 
Internet 10.35.195.17   112 0001.e6a2.5a90 ARPA FastEthernet0/0 
Internet 10.35.195.24   168 0050.564b.ebd4 ARPA FastEthernet0/0 

有具有固定寬度的文本輸入。一些參數,如「硬件地址」,有空格。首先,我使用Text :: CSV :: Slurp,很難定義分隔符。所以我放棄了。

只是想知道,是否有一些Perl模塊或嵌入perl的命令(解壓,SUBSTR)能夠順利和有效地處理這個輸入?

+0

'unpack'可以處理這個,是的'substr'過你爲什麼要問,如果你已經知道有一些關於你不明白的文檔 – TLP 2013-04-07 09:52:02

回答

4

我會用Parse::FixedLength模塊,妥善處理這類問題。這是一個例子:??

use strict; 
use warnings; 
use Parse::FixedLength; 

#define your format in the constructor 
my $pfl = Parse::FixedLength->new([qw(Protocol:10 Addr:34)], {trim=>1}); 

open my $file, '<', 'file_to_be_readed.txt' or die $!; 
<$file> #if your file has a header, forget it 

while(my $line = <$file>) { 
    my $data = $pfl->parse($line); 
    my $protocol = $data->{Protocol}; 
    my $addr = $data->{Addr}; 
    #... 
} 

close $file; 
+0

是,很簡單。 – user2253717 2013-04-07 10:03:40