我正在尝试将 Linux 上的网络接口配置文件列表加载到哈希哈希中,并进一步将它们编码为 JSON。这是我正在使用的代码:
#!/usr/bin/env perl
use strict;
use diagnostics;
use JSON;
use Data::Dumper qw(Dumper);
opendir (DIR, "/etc/sysconfig/network-scripts/");
my @configs =grep(/^ifcfg-*/, readdir(DIR));
my $output = "metadata/json_no_comment";
my %configuration;
my $key;
my $value;
my %temp_hash;
foreach my $input ( @configs) {
$input= "/var/tmp/rhel6.8/" . $input;
open (my $JH, '<', $input) or die "Cannot open the input file $!n";
while (<$JH>) {
s/#.*$//g;
next if /^s*#/;
next if /^$/;
for my $field (split ) {
($key, $value) = split /s*=s*/, $field;
$temp_hash{$key} = $value;
}
$configuration{$input} = %temp_hash;
}
close $JH;
}
print "-----------------------n";
print Dumper %configuration;
print "-----------------------n";
my $json = encode_json %configuration;
open (my $JNH, '>', $output) or die "Cannot open the output file $!n";
print $JNH $json;
close $JNH;
我得到的数据结构如下:
$VAR1 = {
'/etc/sysconfig/network-scripts/ifcfg-lo' => {
'BOOTPROTO' => 'dhcp',
'NAME' => 'loopback',
'TYPE' => 'Ethernet',
'IPV6INIT' => 'yes',
'HWADDR' => '"52:54:00:65:e7:8c"',
'DEVICE' => 'lo',
'NETBOOT' => 'yes',
'NETMASK' => '255.0.0.0',
'BROADCAST' => '127.255.255.255',
'IPADDR' => '127.0.0.1',
'NETWORK' => '127.0.0.0',
'ONBOOT' => 'yes'
},
'/etc/sysconfig/network-scripts/ifcfg-eth0' => $VAR1->{'/etc/sysconfig/network-scripts/ifcfg-lo'}
};
我正在寻找的数据结构如下:
$VAR1 = {
'/etc/sysconfig/network-scripts/ifcfg-lo' => {
'BOOTPROTO' => 'dhcp',
'NAME' => 'loopback',
'TYPE' => 'Ethernet',
'IPV6INIT' => 'yes',
'HWADDR' => '"52:54:00:65:e7:8c"',
'DEVICE' => 'lo',
'NETBOOT' => 'yes',
'NETMASK' => '255.0.0.0',
'BROADCAST' => '127.255.255.255',
'IPADDR' => '127.0.0.1',
'NETWORK' => '127.0.0.0',
'ONBOOT' => 'yes'
},
'/etc/sysconfig/network-scripts/ifcfg-eth0' => {
'BOOTPROTO' => 'dhcp',
'NAME' => '"eth0"',
'TYPE' => 'Ethernet',
'IPV6INIT' => 'yes',
'HWADDR' => '"52:54:00:65:e7:8c"',
'NETBOOT' => 'yes',
'ONBOOT' => 'yes'
}
};
知道我做错了什么吗?为什么第一个嵌套哈希创建正确,第二个没有?我怀疑,这与逐行读取文件有关,但我必须这样做,因为我需要在 JSON 转换之前过滤掉注释的行。感谢您的任何帮助。
编辑:我已经按照鲍罗丁的建议修改了脚本,它可以工作。谢谢!
问题是$configuration{$input}
总是引用相同的哈希%temp_hash
,因为您已在文件级别声明了它。您需要通过在 for
循环中声明%temp_hash
来为每个配置文件创建一个新的哈希
另请注意,next if /^s*#/
可能没有效果,因为您刚刚删除了行中的任何哈希。您的消毒应该看起来像
s/#.*//;
next unless /S/;