在perl中组合2个“深”(多维)哈希

前端之家收集整理的这篇文章主要介绍了在perl中组合2个“深”(多维)哈希前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有一个问题可以解释我想要的内容how to merge 2 deep hashes in perl

但是,那里的答案似乎对我不起作用(使用Merge模块的建议).

我有两个哈希像这样:

$VAR1 = {
          '57494' => {
                       'name' => 'John Smith','age' => '9','height' => '120'
                     },'57495' => {
                       'name' => 'Amy Pond','age' => '17','height' => '168'
                     }
        }
};
$VAR1 = {
          '57494' => {
                       'name_address' => 'Peter Smith','address' => '5 Cambridge Road','post_code' => 'CR5 0FS'
                     }
        }
};

如果我使用Hash :: Merge或%c = {%a,%b}格式,我每次都会得到这个:

$VAR1 = '57494';
$VAR2 = {
          'name_address' => 'Peter Smith','post_code' => 'CR5 0FS'
        };

(所以当我想要时,它基本上用第二个数据覆盖了第一个数据并弄乱了键):

$VAR1 = {
          '57494' => {
                       'name' => 'John Smith','height' => '120'
                       'name_address' => 'Peter Smith','post_code' => 'CR5 0FS'
                     },'height' => '168'
                     }
        }
};

因此,当密钥相同时,数据会合并在一起,否则新密钥只会附加到末尾.我希望这是有道理的.也许我使用Merge做错了一些事情,或者需要“手动”将它们添加到循环中,但无论如何我都会花太多时间思考它!

编辑:我如何使用Merge来查看我是否在做一些愚蠢的事情:

我有:

use Hash::Merge qw( merge );

...hash data above as %hash1 and %hash2...

my %combined_hash = %{ merge( %hash1,%hash2 ) };
print Dumper(%combined_hash);

解决方法

如果我用引用来做它,它就像一个魅力.

use strict; use warnings;
use Data::Dumper;
use Hash::Merge qw(merge);
my $h1 = {
  '57494' => {
    'name'   => 'John Smith','age'    => '9','height' => '120'
  },'57495' => {
    'name'   => 'Amy Pond','age'    => '17','height' => '168'
  }
};

my $h2 = {
  '57494' => {
    'name_address' => 'Peter Smith','address'      => '5 Cambridge Road','post_code'    => 'CR5 0FS'
  }
};

my $h3 = merge( $h1,$h2 );
print Dumper $h3;

输出

$VAR1 = {
      '57495' => {
                   'name' => 'Amy Pond','height' => '168'
                 },'57494' => {
                   'name_address' => 'Peter Smith','name' => 'John Smith','post_code' => 'CR5 0FS','height' => '120','age' => '9'
                 }
    };

但是,如果我使用散列而不是散列引用来执行此操作,则不会:

my %hash1 = (
  '57494' => {
    'name'   => 'John Smith','height' => '168'
  }
);

my %hash2 = (
  '57494' => {
    'name_address' => 'Peter Smith','post_code'    => 'CR5 0FS'
  }
);

my %h3 = merge( %hash1,%hash2 );
print Dumper \%h3;

__END__
$VAR1 = {
  '57495' => undef
};

这是因为Hash::Merge的合并只能接受引用,但是你传递它的哈希值.此外,您需要在标量上下文中调用它.

试试吧:

#                             +--------+--- references
#,-- SCALAR context        |        |
my $combined_hash = %{ merge( \%hash1,\%hash2 ) };
print Dumper($combined_hash);

猜你在找的Perl相关文章