我是Perl的新手。我正在尝试提取存储在文件中的VLAN信息。文件内容,
VLAN0001
Spanning tree enabled protocol rstp
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- --------------------------------
PE8/1 Desg FWD 2 128.2945 P2p Edge
Ta579 Desg FWD 3 128.5761 P2p Edge
VLAN0023
Spanning tree enabled protocol rstp
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- --------------------------------
PE8/1 Desg FWD 2 128.2945 P2p Edge
Ta579 Desg FWD 3 128.5761 P2p Edge
ACCOUNT
Spanning tree enabled protocol rstp
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- --------------------------------
Ta579 Desg FWD 1 128.5764 P2p我有perl代码,
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $filename = "spanning-tree1.txt";
open my $fh, '<', $filename or die "error opening $filename: $!";
my $data = do { local $/; <$fh> };
my @list = ($data =~ /(^[A-Za-z0-9]+.*?(?=^[A-Za-z0-9]+$|\Z))/msg);
#print Dumper($data);
#print "\n##############################################\n";
print Dumper(\@list);它的输出是
$VAR1 = [
'VLAN0001
Spanning tree enabled protocol rstp
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- --------------------------------
PE8/1 Desg FWD 2 128.2945 P2p Edge
Ta579 Desg FWD 3 128.5761 P2p Edge
VLAN0023
Spanning tree enabled protocol rstp
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- --------------------------------
PE8/1 Desg FWD 2 128.2945 P2p Edge
Ta579 Desg FWD 3 128.5761 P2p Edge
ACCOUNT
Spanning tree enabled protocol rstp
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- --------------------------------
Ta579 Desg FWD 1 128.5764 P2p'
];我需要输出(@list)
$VAR1 = [
'VLAN0001
Spanning tree enabled protocol rstp
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- --------------------------------
PE8/1 Desg FWD 2 128.2945 P2p Edge
Ta579 Desg FWD 3 128.5761 P2p Edge
',
'VLAN0023
Spanning tree enabled protocol rstp
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- --------------------------------
PE8/1 Desg FWD 2 128.2945 P2p Edge
Ta579 Desg FWD 3 128.5761 P2p Edge
',
'ACCOUNT
Spanning tree enabled protocol rstp
Interface Role Sts Cost Prio.Nbr Type
------------------- ---- --- --------- -------- --------------------------------
Ta579 Desg FWD 1 128.5764 P2p'
];有趣的是,我在@list 中得到了适当的值,当输入作为字符串给出,而不是从文件中读取。。
发布于 2014-12-11 10:37:33
你可以用数字和大写字母在行的开头分割整串,
my @list = split /(?= ^[A-Z0-9]+\s*$ )/mx, do { local $/; <DATA> };发布于 2014-12-11 10:18:29
有时regex并不是唯一的解决方案:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $inc = -1;
my @list;
my $filename = "spanning-tree1.txt";
open my $fh, '<', $filename or die "error opening $filename: $!";
while (<$fh>) {
/^[A-Z0-9]+\s*$/ and $inc++;
$list[$inc] .= $_;
}
print Dumper(\@list);
close $fh;https://stackoverflow.com/questions/27418365
复制相似问题