Hi there. I'm trying to merge two hashes, which may contain some of the same keys, to produce another hash with the values summed.

For example, if both hashes looked like this:

%Hash1 key 1 => '1' key 15 => '3' key 150 => '1'
%Hash2 key 1 => '1' key 15 => '1' key 140 => '1'

I would like the final hash to look like this:

%CombinedHash key 1 => '2' key 15 => '4' key 140 => '1' key 150 => '1'

I hope this makes sense? I have included a fragment of code that does not work properly, below - upon testing I've found that it doesn't sum the values correctly, just a '1' if the key/val pair was not merged and a '2' if it was. I suppose I could do something with a loop to iterate over each hash in turn? I'd really appreciate any help with this.

my %muthash = ( key1 => '1', key15 => '3', key150 => '1', ); my %copyhash ( key1 => '1', key15 => '1', key140 => '1', ); my %mergedhash; %mergedhash = map {$_=> $muthash{$_} + $copyhash{$_} } (keys %muthash, +keys %copyhash);

This is just where I'd like to put the data afterwards - included for reference.

my $fileoutput = $name." COMB".".csv"; open (OUTPUT,">Input/$fileoutput") or die "Could not open output file\ +n"; foreach my $gene (keys %mergedhash) { print OUTPUT "$gene",",","$mergedhash{$gene}","\n"; } close (OUTPUT);

UPDATE: Thanks for your input guys! It turns out I'm a flipping idiot and wasn't populating my hashes properly in the first place. You're all heroes though, and iterating through your solutions has taught me things. Thanks again!


In reply to Merging two hashes, keeping keys unique but adding values if necessary by Majestic

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.