2

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

正常合并会好吗?

如果这是重复,我很抱歉,但我尝试查找但没有出现这样的具体内容。

谢谢!

4

2 回答 2

9

要将 %hoa2 合并到 %hoa1:

for (keys(%hoa2)) {
   push @{ $hoa1{$_} }, @{ $hoa2{$_} };
}
于 2012-12-12T06:48:49.437 回答
3

这些散列的值是数组引用。

#!/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
                 ]
        };

希望有帮助。

于 2012-12-12T06:58:10.160 回答