将两个哈希合并到 %hash1 中的最佳方法是什么?我一直知道 %hash2 和 %hash1 总是有唯一的键。如果可能的话,我也更喜欢一行代码。
$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';
最佳答案
快速回答(TL;DR)
%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
概述
- 上下文:Perl 5.x
- 问题:用户希望将两个哈希值1合并为一个变量
解决方案
- 对简单变量使用上面的语法
- 对复杂的嵌套变量使用 Hash::Merge
陷阱
- 当两个哈希都包含一个或多个重复键时该怎么办
- 具有空值的键值对是否应该覆盖具有非空值的键值对?
- 首先什么构成了空值和非空值? (例如,
undef
、零、空字符串、false
、falsy ...)
- 首先什么构成了空值和非空值? (例如,
另请参阅
- PM post on merging hashes
- PM Categorical Q&A hash union
- Perl Cookbook 5.10. Merging Hashes
- websearch://perlfaq“合并两个哈希值”
- websearch://perl 合并哈希
- https://metacpan.org/pod/Hash::Merge
脚注
1 *(又名 associative-array 、又名 dictionary )
关于perl - 如何在 Perl 中组合哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/350018/