从其他哈希数组中添加键和值

时间:2014-08-21 10:15:11

标签: arrays perl hash

我有两个哈希数组。它们中有相似的值但是我想在哈希中创建新键,它将具有第二个哈希数组的某些值。

First Array:

[
    { area_code => 93,   name => 'Afghanistan',    code => 'AF', slno => 4554 },
    { area_code => 1684, name => 'American Samoa', code => 'AS', slno => 4557 },
];

第二阵列:

[
    { city => "Berat",  country => "AS", id => 134368 },
    { city => "Durres", country => "AS", id => 138466 },
    { city => "Kabul",  country => "AF", id => 142462 },
];

现在在第一个哈希中,我有密钥代码,其值类似于第二个哈希键 country 。所以我想在第二个数组中添加一个新密钥哈希将是 country_name country_name 值将是哈希名称的第一个数组的值。

那么我们怎么做才能帮助我呢

2 个答案:

答案 0 :(得分:4)

use strict;
use warnings;

my $a1 = [
    { area_code => 93,   code => "AF", name => "Afghanistan",    slno => 4554 },
    { area_code => 1684, code => "AS", name => "American Samoa", slno => 4557 },
];

my $a2 = [
    { city => "Berat",  country => "AS", id => 134368 },
    { city => "Durres", country => "AS", id => 138466 },
    { city => "Kabul",  country => "AF", id => 142462 },
];

my %h = map { $_->{code} => $_ } @$a1;
for my $v (@$a2) {
    $v->{country_name} = $h{ $v->{country} }{name};
}

答案 1 :(得分:3)

这与@ mpapec相似,但我认为,它更清洁。

use strict;
use warnings;

my @array1 = (
   { area_code => 93,   name => 'Afghanistan',    code => 'AF', slno => 4554 },
   { area_code => 1684, name => 'American Samoa', code => 'AS', slno => 4557 },
);

my @array2 = (
   { country => 'AS', city => 'Berat',  id => 134368 },
   { country => 'AS', city => 'Durres', id => 138466 },
   { country => 'AF', city => 'Kabul',  id => 142462 },
);

{
   my %names = map { $_->{code} => $_->{name} } @array1;
   $_->{country_name} = $names{ $_->{country} } for @array2;
}

use Data::Dump;
dd \@array2;

<强>输出

[
  {
    country      => 'AS',
    city         => 'Berat',
    id           => 134368,
    country_name => 'American Samoa',
  },
  {
    country      => 'AS',
    city         => 'Durres',
    id           => 138466,
    country_name => 'American Samoa',
  },
  {
    country      => 'AF',
    city         => 'Kabul',
    id           => 142462,
    country_name => 'Afghanistan',
  },
]