in reply to Generate union of the two hashes

As the thing you want to output is a hash ref, the statement print $h3 will output something like HASH(0x182f384). You will get something closer to your expected output by using Data::Dumper, swapping your print statement for use Data::Dumper; print Dumper $h3;. See How can I visualize my complex data structure? for more information.

The reason you are clobbering your initial hash is because your structure is a hash of hashes, so while they are different at the base level, you have the same object (a hash reference) associated with the key drug comparison. To make a shallow copy, I usually use Data::Dumper again, this time in an eval in a do:

my $h1 = { 'drug comparison' => { '7003000.xml' => { 'entity' => 'a1, a2, a3' }, '70037559.xml' => { 'entity' => 'x1, x2, x3' } } }; my $copy = do{my $VAR1; eval Dumper $h1; $VAR1;};
I would suggest making the copy in your union_of_h1_h2 sub.

Replies are listed 'Best First'.
Re^2: Generate union of the two hashes
by shan_emails (Beadle) on Sep 08, 2010 at 15:19 UTC
    Hi All,

    Thanks for all your answers.

    now i used "Clone" module. so the address of the copying hash has been changed. so now the changes affected only in h3 hash.

    use Clone qw(clone); $h1 = { 'drug comparison' => { '7003000.xml' => { 'entity' => 'a1, a2, a3' }, '70037559.xml' => { 'entity' => 'x1, x2, x3' } } }; $h2 = { 'drug comparison' => { '7004562.xml' => { 'entity' => 'z1, z2, z3' }, '70037559.xml' => { 'entity' => 'e1, e2, e3' } } }; $h3 = union_of_h1_h2 ($h1, $h2); print $h3; sub union_of_h1_h2 { my ($ai, $ref) = @_; my $output = clone($ai); foreach my $_ref (keys %$ref) { unless (exists $output->{$_ref}) { $output->{$_ref} = $ref->{$_ref}; }else { foreach my $filename (keys %{$ref->{$_ref}}) { if (!exists $output->{$_ref}->{$filename}) { $output->{$_ref}->{$filename} = $ref->{$_ref}->{$f +ilename}; } } } } return $output; }


    Wishes
    Shanmugam A.