Quick Answer (TL;DR)
%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
Overview
- Context: Perl 5.x
- Problem: The user wishes to merge two hashes1 into a single variable
Solution
- use the syntax above for simple variables
- use Hash::Merge for complex nested variables
Pitfalls
- What do to when both hashes contain one or more duplicate keys
- Should a key-value pair with an empty value ever overwrite a key-value pair with a non-empty value?
- What constitutes an empty vs non-empty value in the first place? (e.g.
undef
, zero, empty string,false
, falsy …)
- What constitutes an empty vs non-empty value in the first place? (e.g.
See also
- PM post on merging hashes
- PM Categorical Q&A hash union
- Perl Cookbook 5.10. Merging Hashes
- websearch://perlfaq “merge two hashes”
- websearch://perl merge hash
- https://metacpan.org/pod/Hash::Merge
Footnotes
1 * (aka associative-array, aka dictionary)