How to combine 2 deep hashes in perl

I am writing sub in Perl to merge 2 hashes of the same structure; so merge ($ a, $ b)

$a = {
 k1 => { sk1 => 'v1' },
 k2 => { sk3 => 'v3', sk4 => 'v4' }
};
$b = {
 k1 => { sk2 => 'v2'},
 k3 => { sk5 => 'v5'} 
};

will result in

$c = {
 k1 => { sk1 => 'v1', sk2 => 'v2' },
 k2 => { sk3 => 'v3', sk4 => 'v4' }
 k3 => { sk5 => 'v5'} 
};

Below is my merge code and it does not work. How can i fix this? Thank.

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;
}
+3
source share
2 answers

If you do not do this, to find out how to do it, I would use a ready-made solution, for example Hash :: Merge or Hash :: Union :: Simple .

+8
source

This should be good enough:

for my $href ($a, $b) {
    while (my($k,$v) = each %$href) {
        $c->{$k} = $v;
    }
}

If you do not want to duplicate duplicates, perhaps because you are worried about problems with ordering, use:

for my $href ($a, $b) {
    while (my($k,$v) = each %$href) {
        push @{ $c->{$k} },  $v;
    }
}

, Perl, .

, , . .

each keys, , DBM .

+2

Source: https://habr.com/ru/post/1772283/


All Articles