Merging hashes in Perl
Recently I needed to merge two Perl hashes such that the values of the merged hash would be the sum of the two hashes whenever the keys were the same and just the value of one hash whenever they were unique.
I found several examples of merging hashes on the Internet but none did exactly what I needed. This is a common example:
%mergedhash = (%hash1, %hash2);
This method does make the keys of %mergedhash the union of the other hash's keys. However, when the keys of the two hashes are the same the values of %mergedhash simply take on the values of the second hash in the list (%hash2), not the addition of %hash1 and %hash2 values as I needed.
Obviously, one could write a loop to do this but I wanted something faster because I was dealing with very large hashes.
The solution I found uses the map function:
%mergedhash = map { $_ => $hash1{$_} + $hash2{$_} } (keys %hash1, keys %hash2);
Another way is to combine the two methods:
%mergedhash = (%hash1, %hash2);
%mergedhash = map { $_ => $hash1{$_} + $hash2{$_} } keys %mergedhash;
The advantage here is that the map function is not adding the two values two separate times; it is receiving the keys only once, not twice as in the prior example. I haven't check to see which is faster. If you do, let me know what you find out!
I found several examples of merging hashes on the Internet but none did exactly what I needed. This is a common example:
%mergedhash = (%hash1, %hash2);
This method does make the keys of %mergedhash the union of the other hash's keys. However, when the keys of the two hashes are the same the values of %mergedhash simply take on the values of the second hash in the list (%hash2), not the addition of %hash1 and %hash2 values as I needed.
Obviously, one could write a loop to do this but I wanted something faster because I was dealing with very large hashes.
The solution I found uses the map function:
%mergedhash = map { $_ => $hash1{$_} + $hash2{$_} } (keys %hash1, keys %hash2);
Another way is to combine the two methods:
%mergedhash = (%hash1, %hash2);
%mergedhash = map { $_ => $hash1{$_} + $hash2{$_} } keys %mergedhash;
The advantage here is that the map function is not adding the two values two separate times; it is receiving the keys only once, not twice as in the prior example. I haven't check to see which is faster. If you do, let me know what you find out!
