Majestic has asked for the wisdom of the Perl Monks concerning the following question:
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!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Merging two hashes, keeping keys unique but adding values if necessary
by LanX (Saint) on Jun 04, 2014 at 15:55 UTC | |
|
Re: Merging two hashes, keeping keys unique but adding values if necessary
by LanX (Saint) on Jun 04, 2014 at 16:24 UTC | |
|
Re: Merging two hashes, keeping keys unique but adding values if necessary
by tangent (Parson) on Jun 04, 2014 at 18:41 UTC | |
|
Re: Merging two hashes, keeping keys unique but adding values if necessary
by baxy77bax (Deacon) on Jun 04, 2014 at 15:59 UTC | |
by LanX (Saint) on Jun 04, 2014 at 16:04 UTC | |
|
Re: Merging two hashes, keeping keys unique but adding values if necessary
by perlfan (Parson) on Jun 05, 2014 at 13:15 UTC |