Perl中的合并哈希:特殊情况

Perl中的合并哈希:特殊情况,perl,perl-data-structures,Perl,Perl Data Structures,如何在perl中合并两个散列,其中键可能发生冲突,并且值是数组。? 如果发生冲突,我希望合并值数组 正常合并可以吗 如果这是重复的话,我很抱歉,但我试着向上看,但没有找到如此具体的结果 谢谢 要将%hoa2合并到%hoa1中: for (keys(%hoa2)) { push @{ $hoa1{$_} }, @{ $hoa2{$_} }; } 这些散列的值是数组引用 #!/usr/bin/perl -Tw use strict; use warnings; use Data::Dump

如何在perl中合并两个散列,其中键可能发生冲突,并且值是数组。? 如果发生冲突,我希望合并值数组

正常合并可以吗

如果这是重复的话,我很抱歉,但我试着向上看,但没有找到如此具体的结果


谢谢

要将%hoa2合并到%hoa1中:

for (keys(%hoa2)) {
   push @{ $hoa1{$_} }, @{ $hoa2{$_} };
}

这些散列的值是数组引用

#!/usr/bin/perl -Tw

use strict;
use warnings;
use Data::Dumper;

# The array ref of the first hash will be clobbered by
# the value of the second.
{
    my %hash_a = ( a => [ 1, 2, 3 ] );
    my %hash_b = ( a => [ 4, 5, 6 ] );

    @hash_a{qw( a )} = @hash_b{qw( a )};

    print Dumper( \%hash_a );
}

#  To merge the values of the arrays you'd need to handle that like this.
{
    my %hash_a = ( a => [ 1, 2, 3 ] );
    my %hash_b = ( a => [ 4, 5, 6 ] );

    @{ $hash_a{a} } = ( @{ $hash_a{a} }, @{ $hash_b{a} } );

    print Dumper( \%hash_a );
}
该程序的输出为:

$VAR1 = {
          'a' => [
                   4,
                   5,
                   6
                 ]
        };
$VAR1 = {
          'a' => [
                   1,
                   2,
                   3,
                   4,
                   5,
                   6
                 ]
        };

希望能有帮助。

你必须自己做。在一个散列上迭代,在另一个散列中查找,为每个冲突合并数组。除了缺少循环之外,这还不完整,因为它假设两个散列中都存在密钥。我的回答旨在说明数据结构是如何工作的。我不希望它是一个复制粘贴解决方案。我没有抓住要点吗?我喜欢简洁的解决方案。然后你会喜欢推{$hoa1{${$}},{$hoa2{$}键(%hoa2):)