我正在尝试使用此代码将lshw
输出解析为哈希值,到目前为止有效。
use strict;
use warnings;
my (%lshw,$key,$value);
while (<>){
s/#.*//; # no comments
s/^\s+//; # no leading whites
s/\s+$//; # no trailing whites
next unless length; # anything left?
if (/(?<key>.*?):\s+(?<value>.*)/x){
$lshw{$+{key}} = $+{value};
}
}
# remove white spaces in hash keys
for $key (keys %lshw){
$value = delete $lshw{$key};
for ($key){
s/\s+//g;
}
$lshw{$key} = $value;
}
my $logname = $lshw{'logicalname'};
print "Logical name\t $logname\n";
但是当我使用以下配置来到这一行时,我感到很震惊:
clock: 33Mhz
width: 32 bits
capacity: 1Gbit/s
configuration:autonegotiation=on broadcast=yes driver=igb driverversion=5.3.0-k duplex=full firmware=1.63, 0x800009fa ip=[REMOVED] latency=0 link=yes multicast=yes port=twisted pair speed=1Gbit/s`
我正在尝试一种方法,但没有找到解决方法如何分割键/值,因为它包含多个单词值,如port=twisted pair
。
关键始终是一个单词。
任何人都可以给我一个如何解决这个问题的提示吗?
(感谢simbabque的严格/警告提示)
答案 0 :(得分:4)
您需要的是捕获等号后面的所有字符,而不是模式somekeyname=
。
#!/usr/bin/env perl
use strict;
use warnings;
my $s = q{configuration: autonegotiation=on broadcast=yes driver=igb driverversion=5.3.0-k duplex=full firmware=1.63, 0x800009fa ip=[REMOVED] latency=0 link=yes multicast=yes port=twisted pair speed=1Gbit/s};
my ($key, $rest) = split /:\s*/, $s, 2;
my %params = ($rest =~ / (\w+) = ((?:. (?! \w+ = ))+) /gx);
use YAML::XS;
print Dump \%params;
输出:
---
autonegotiation: on
broadcast: yes
driver: igb
driverversion: 5.3.0-k
duplex: full
firmware: 1.63, 0x800009fa
ip: '[REMOVED]'
latency: '0'
link: yes
multicast: yes
port: twisted pair
speed: 1Gbit/s
此外,您的初始循环可以改进:
while (<>) {
next if /^#/; # skip comments
/\S/ or next; # skip blank lines
s/^\s+//;
s/\s+\z//;
# ...
}
答案 1 :(得分:1)
您只需要split
配置字符串
use strict;
use warnings 'all';
use feature 'say';
my $s = 'configuration: autonegotiation=on broadcast=yes driver=igb driverversion=5.3.0-k duplex=full firmware=1.63, 0x800009fa ip=[REMOVED] latency=0 link=yes multicast=yes port=twisted pair speed=1Gbit/s';
say for split /\s+(?=[^\s=]+=)/, $s;
configuration:
autonegotiation=on
broadcast=yes
driver=igb
driverversion=5.3.0-k
duplex=full
firmware=1.63, 0x800009fa
ip=[REMOVED]
latency=0
link=yes
multicast=yes
port=twisted pair
speed=1Gbit/s
您现在有一个键列表及其值,正确地按键名称划分。这应该很容易处理
答案 2 :(得分:0)
鲍罗丁的方法就是它。
如果你想用regexp解析它,这将有效并将键与其值分开。
#!/usr/bin/env perl
use warnings FATAL => 'all';
use strict;
my $s = 'configuration: autonegotiation=on broadcast=yes driver=igb driverversion=5.3.0-k duplex=full firmware=1.63, 0x800009fa ip=[REMOVED] latency=0 link=yes multicast=yes port=twisted pair speed=1Gbit/s';
while ($s =~ m/(?<key>[A-Za-z0-9]+)=(?<value>([\/\[\]A-Za-z0-9., -]+)(?= [a-z]+)|([\/\[\]A-Za-z0-9., -]+))/g) {
print "$+{key} >> $+{value}\n";
$s =~ s/$+{key}//;
}
<强>输出强>
autonegotiation >> on
broadcast >> yes
driver >> igb
driverversion >> 5.3.0-k
duplex >> full
firmware >> 1.63, 0x800009fa
ip >> [REMOVED]
latency >> 0
link >> yes
multicast >> yes
port >> twisted pair
speed >> 1Gbit/s
<强>赞成强>
<强>缺点强>
重构提案
[\/\[\]A-Za-z0-9., -]