Q:

Merge Hashes in Perl: Special Case

How to merge two hashes in perl where keys can collide and the values are arrays.?
In case of collision I want to merge the value arrays.
Would normal merge be just fine?
I am sorry if this is a repetition, but I tried looking up but nothing such specific turned up.
Thanks!

A:

To merge %hoa2 into %hoa1:
for (keys(%hoa2)) {
   push @{ $hoa1{$_} }, @{ $hoa2{$_} };
}

A:

The values of these hashes are array references.
#!/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 );
}

The output of this program is:
$VAR1 = {
          'a' => [
                   4,
                   5,
                   6
                 ]
        };
$VAR1 = {
          'a' => [
                   1,
                   2,
                   3,
                   4,
                   5,
                   6
                 ]
        };

Hope that helps.

