How to merge two hashes in Perl?
Question
How to merge two hashes in Perl?
Merging two hashes in Perl is a common operation when you want to combine key-value pairs from multiple sources into one hash. Perl offers flexible ways to achieve this, taking advantage of its "There's More Than One Way To Do It" (TMTOWTDI) philosophy.
Basic Hash Merge Using Slice Assignment
The simplest and most idiomatic way to merge two hashes %hash1 and %hash2 is to copy all keys and values from one hash into the other using a hash slice. For example:
#!/usr/bin/perl
use strict;
use warnings;
my %hash1 = (apple => 3, banana => 5);
my %hash2 = (orange => 2, banana => 7);
# Merge %hash2 into %hash1 (overwrites duplicate keys with %hash2 values)
@hash1{keys %hash2} = values %hash2;
# Print merged hash to verify
while (my ($key, $value) = each %hash1) {
print "$key => $value\n";
}
Output:
banana => 7 apple => 3 orange => 2
Here’s what happens:
@hash1{keys %hash2}is a hash slice, representing all keys from%hash2in%hash1.- Assigning
values %hash2overwrites those keys in%hash1or adds them if they do not exist. - Keys collisions will result in values from
%hash2prevailing.
Preserving Original Hashes
If you want to create a third hash with the merged data, without modifying the originals, you can combine hashes in list context and use a hash assignment:
#!/usr/bin/perl
use strict;
use warnings;
my %hash1 = (apple => 3, banana => 5);
my %hash2 = (orange => 2, banana => 7);
my %merged = (%hash1, %hash2);
while (my ($k, $v) = each %merged) {
print "$k => $v\n";
}
The comma list (%hash1, %hash2) essentially concatenates the key-value pairs of both hashes. When they are converted into a new hash, the keys in %hash2 will overwrite any duplicates from %hash1. This is handy for one-liner merges or when you want the merged outcome separate.
Context and Gotchas
- Context matters: Hashes flatten into lists of key-value pairs; watch out for unexpected flattening and ordering due to Perl’s internal hashing.
- Duplicate key precedence: Values from the last hash listed overwrite previous values for duplicate keys.
- References: If merging hashes with references as values, you might want a deep merge—this approach only merges the top-level keys.
- Perl versions: This technique works identically on all Perl 5 versions because it’s core hash/list operations—no special version features required.
Summary
To merge two hashes in Perl:
- Use
@hash1{keys %hash2} = values %hash2;to merge in-place, modifying one hash. - Use
my %merged = (%hash1, %hash2);to create a new merged hash. - Remember duplicates are overwritten by the latter hash’s values.
These simple methods offer concise, efficient, and readable ways to combine hashes in Perl following its idiomatic style.
Verified Code
Executed in a sandbox to capture real output. • v5.34.1 • 8ms
apple => 3
banana => 7
orange => 2
(empty)