我是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
)as,
$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
中获得了正确的值,输入是以字符串形式提供的,而不是从文件中读取。
答案 0 :(得分:3)
有时正则表达式不是唯一的解决方案:
#!/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;
答案 1 :(得分:2)
您可以在行的开头拆分整个字符串,后跟数字和大写字母
my @list = split /(?= ^[A-Z0-9]+\s*$ )/mx, do { local $/; <DATA> };