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