# Deep Merges two hashes and returns the resulting hash # The hashes must have a similar structure - the following is an error +: # hash1: {a => {b => 2}} # hash2: {a => 1} # sub hash_merge { my ($hash1,$hash2,$visited) = @_; # Protect against infinite recursion if ($visited->{$hash1} || $visited->{$hash2}) { return; } $visited->{$hash1} = 1; $visited->{$hash2} = 1; my %rhash = (); my %unique_keys = map {$_ => 0} (keys %$hash1, keys %$hash2); for my $key (keys %unique_keys) { # Store whether the key exists in each hash, # this makes the logic below a little more readable. # Note that 'exists' is checked - this is to allow # overrides with '0', undef, etc. my $e1 = exists $hash1->{$key}; my $e2 = exists $hash2->{$key}; if (!$e1 && $e2) { $rhash{$key} = $hash2->{$key}; } elsif ($e1 && !$e2) { $rhash{$key} = $hash1->{$key}; } else { if (ref($hash1->{$key}) eq 'HASH') { $rhash{$key} = hash_merge($hash1->{$key},$hash2->{$key +},$visited); } else { $rhash{$key} = $hash2->{$key}; } } } return \%rhash; } my %a = ( k1 => 1, k2 => { kk3 => 3 }, ); my %b = ( k1 => 5, k2 => { kk4 => 4 }, ); my $c = hash_merge(\%a,\%b); use Data::Dumper; $Data::Dumper::Sortkeys = 1; print Dumper($c);
The output should be:
$VAR1 = { 'k1' => 5, 'k2' => { 'kk3' => 3, 'kk4' => 4 } };
This implementation is a little simplistic, but it gets the job done.

In reply to Re^2: adding to hashes by imp
in thread adding to hashes by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.