What is the best way to combine both hashes into %hash1? I always know that %hash2 and %hash1 always have unique keys. I would also prefer a single line of code if possible.
$hash1{'1'} = 'red'; $hash1{'2'} = 'blue'; $hash2{'3'} = 'green'; $hash2{'4'} = 'yellow';
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
- (see e.g., Perl - Merge hash containing duplicate keys)
- (see e.g., Perl hashes: how to deal with duplicate keys and get possible pair)
- 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 ...)
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)