If you want to write a recursive procedure, you might want the filter the common keys that point to hash refs, apply the procedure to them, and then use Corion's "simple" method.
use Array::Utils qw( intersect ); my @refkeys1 = grep { ref $ref1->{$_} } keys %$ref1; my @refkeys2 = grep { ref $ref2->{$_} } keys %$ref2; my @common = intersect( @refkeys1, @refkeys2 );
UPDATE: Here is a complete example which I only tested on your data provided. As with all recursive procedures more testing would be needed...
use strict; use warnings; use Data::Dumper; use Array::Utils qw( intersect ); my $ref1={ ref1_specific_key => 'some value', common_key => { a => 1, common_subkey => 'foo' } }; my $ref2= { ref2_specific_key => 'some other value', common_key => { b => 2, common_subkey => 'bar' } }; sub mergehash { my ($ref1, $ref2) = @_; my @refkeys1 = grep { ref $ref1->{$_} } keys %$ref1; my @refkeys2 = grep { ref $ref2->{$_} } keys %$ref2; my @common = intersect( @refkeys1, @refkeys2 ); for my $c (@common) { $ref2->{$c} = mergehash( $ref1->{$c}, $ref2->{$c} ); } return { %$ref1, %$ref2 }; } my $output = mergehash($ref1,$ref2); print Dumper $output;
In reply to Re^5: What is the easiest way to merge two hashes?
by hdb
in thread What is the easiest way to merge two hashes?
by tkguifan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |