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!
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |