I write a sub in Perl to merge 2 hashes of the same structure; so that merge($a,$b)
$a = {
k1 => { sk1 => 'v1' },
k2 => { sk3 => 'v3', sk4 => 'v4' }
};
$b = {
k1 => { sk2 => 'v2'},
k3 => { sk5 => 'v5'}
};
would result in
$c = {
k1 => { sk1 => 'v1', sk2 => 'v2' },
k2 => { sk3 => 'v3', sk4 => 'v4' }
k3 => { sk5 => 'v5'}
};
Below is my code for merge, and it does not work. How can I correct it? Thank you.
sub merge {
my ($old,$new) = @_;
foreach my $k (keys($old)) {
if (exists $new->{$k}) {
if (ref($old->{$k}) eq 'HASH') {
merge($old->{$k},$new->{$k});
} else {
$new->{$k} = $old->{$k};
}
} else {
$new->{$k} = $old->{$k};
}
}
return $new;
}