我有这样的字典。
print Dumper($emp)
$VAR1 = {
'mike' => {
'country' => {
'US' => {
'pop' => 100
}
}
}
}
我想在其中添加一个新条目'country'
。
$VAR1 = {
'mike' => {
'country' => {
'US' => {
'pop' => 100
},
'Canada' => {
'pop' => 101
}
}
}
}
现在我正在这样建造
$emp -> {$name}{country} = getCountry();
sub getCountry{
....
return country;
}
目前还不清楚getCountry
返回什么。看到它是一个单一的标量,我将假定它是由名称(尽管有名称)键入的国家的哈希。
{ Canada => { pop => 101 } }
合并两个哈希的一种简单方法是
%h = ( %h, %new );
所以
%{ $emp->{$name}{country} } = (
%{ $emp->{$name}{country} },
%{ getCountry() },
);
如果getCountry
要返回国家/地区的名称和国家/地区,则可以使用以下代码:
my ($country_name, $country) = getCountry();
$emp->{$name}{country}{$country_name} = $country;
因此,如果返回的哈希getCountry
值仅返回一个国家/地区,那么您也可以执行以下操作而无需更改getCountry
:
my ($country_name, $country) = %{ getCountry() };
$emp->{$name}{country}{$country_name} = $country;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句