按照我理解问题的方式,您有两个具有相同键的哈希。如果第一个没有某个键的值,你想把另一个哈希的值放在那里。
因为您没有提供如何创建这些哈希,所以我想出了自己的解决方案。您可能可以忽略它。我使用Config::General 和一些技巧来摆脱" 和: 来读取pid 文件,并使用JSON 来读取JSON。
use strict;
use warnings;
use Config::General;
use JSON 'decode_json';
use Data::Dumper;
# read the pid file
my %cfg_pid = Config::General->new(
-NormalizeOption => sub { my $x = shift; $x =~ s/^"|":$//g; $x; },
-NormalizeValue => sub { my $x = shift; $x =~ s/^"|"$//g; $x },
-ConfigFile => \*DATA
)->getall;
# read the json file
my $json = <<'JSON';
{
"connection": {
"file": {
"file_connection_1": {
"CLOUD_AUTHENTICATION": "",
"CLOUD_CONN_PROTOCOL": "",
"CONN_NAME": "file_connection_1",
"FILE_DIR": "/home/directory"
}
}
}
}
JSON
my $cfg_json = decode_json($json);
# this is before
print Dumper $cfg_json;
# actual part that you want
foreach my $key ( keys %{ $cfg_pid{General} } ) {
$cfg_json->{connection}->{file}->{file_connection_1}->{$key} = $cfg_pid{General}->{$key}
unless $cfg_json->{connection}->{file}->{file_connection_1}->{$key};
}
# and this is after
print Dumper $cfg_json;
__DATA__
<General>
"CLOUD_AUTHENTICATION": "YES"
"CLOUD_CONN_PROTOCOL": "PRTCL"
"CONN_NAME": "file_connection_1"
"FILE_DIR": "/home/directory"
</General>
它真正做的只是迭代 pid 文件散列的键,并检查 json 散列是否存在该键的值。如果该值不为真(这意味着键不存在,值为undef,空字符串q{} 或0),它会将其设置为pid 文件哈希的值。当然,您也可以显式检查空字符串。
输出如下。
$VAR1 = {
'connection' => {
'file' => {
'file_connection_1' => {
'FILE_DIR' => '/home/directory',
'CONN_NAME' => 'file_connection_1',
'CLOUD_CONN_PROTOCOL' => '',
'CLOUD_AUTHENTICATION' => ''
}
}
}
};
$VAR1 = {
'connection' => {
'file' => {
'file_connection_1' => {
'FILE_DIR' => '/home/directory',
'CONN_NAME' => 'file_connection_1',
'CLOUD_CONN_PROTOCOL' => 'PRTCL',
'CLOUD_AUTHENTICATION' => 'YES'
}
}
}
};