我想将一些文本解析成一个表格,如下所示:
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有固定宽度的文本输入。 一些Params,例如“Hardware Addr”,中有空格。 首先,我使用Text :: CSV :: Slurp,很难定义分隔符。 所以我放弃了。
只是想知道,是否有一些perl模块或嵌入式perl命令(unpack,substr)可以平滑有效地处理这个输入?
I would like to parse the some text into a table which showing below:
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/0There are text inputs with fixed width. Some Params ,such as "Hardware Addr", have whitespace in it. At the first, I use Text::CSV::Slurp, it is difficult to define separator. So i give up.
Just like to know, are there some perl modules or embedded perl command (unpack, substr)can process this input smoothly and efficiently?
最满意答案
我使用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;I'd use Parse::FixedLength module, which handles properly this kind of problems. This is an example:
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;更多推荐
发布评论