在perl中的另一个字典中追加字典

Append dict in another dict in perl

我有这样的字典。

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 return 是什么。鉴于它是单个标量,我将假设它是按名称键入的国家/地区的哈希值,尽管有名称。

{ Canada => { pop => 101 } }

合并两个散列的简单方法是

%h = ( %h, %new );

所以

%{ $emp->{$name}{country} } = (
   %{ $emp->{$name}{country} },
   %{ getCountry() },
);

如果 getCountry 是 return 国家的名称和国家,您可以使用以下内容:

my ($country_name, $country) = getCountry();
$emp->{$name}{country}{$country_name} = $country;

因此,如果由 getCountry return 编辑的散列 return 只是一个国家,您还可以在不更改 getCountry 的情况下执行以下操作:

my ($country_name, $country) = %{ getCountry() };
$emp->{$name}{country}{$country_name} = $country;