2013-04-07 59 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