如何在perl中合并两个哈希值,其中键可能会发生碰撞而值是数组。 如果发生冲突,我想合并值数组。
正常合并会不会很好?
我很抱歉,如果这是一个重复,但我试着抬头,但没有这样的具体出现。
谢谢!
答案 0 :(得分:9)
将%hoa2合并到%hoa1:
for (keys(%hoa2)) {
push @{ $hoa1{$_} }, @{ $hoa2{$_} };
}
答案 1 :(得分: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
]
};
希望有所帮助。