将两个哈希值合并到%hash1的最佳方法是什么?我总是知道%hash2和%hash1总是有唯一的密钥。如果可能的话,我也更喜欢一行代码。
$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';
答案 0 :(得分:157)
%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
undef
,零,空字符串,false
,falsy ......)1 *(又名associative-array,又名dictionary)
答案 1 :(得分:38)
结帐perlfaq4: How do I merge two hashes。 Perl文档中已经有很多好的信息,您可以立即使用它,而不是等待其他人回答它。 :)
在您决定合并两个哈希值之前,如果两个哈希值都包含相同的键并且您希望保留原始哈希值,则必须决定该怎么做。
如果要保留原始哈希值,请将一个哈希值(%hash1)复制到新哈希值(%new_hash),然后将其他哈希值中的键(%hash2)添加到新哈希值。检查密钥是否已存在在%new_hash中,您有机会决定如何处理重复项:
my %new_hash = %hash1; # make a copy; leave %hash1 alone
foreach my $key2 ( keys %hash2 )
{
if( exists $new_hash{$key2} )
{
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else
{
$new_hash{$key2} = $hash2{$key2};
}
}
如果您不想创建新哈希,您仍然可以使用此循环技术;只需将%new_hash更改为%hash1。
foreach my $key2 ( keys %hash2 )
{
if( exists $hash1{$key2} )
{
warn "Key [$key2] is in both hashes!";
# handle the duplicate (perhaps only warning)
...
next;
}
else
{
$hash1{$key2} = $hash2{$key2};
}
}
如果您不关心一个哈希值会覆盖另一个哈希值中的键和值,您可以使用哈希切片将一个哈希值添加到另一个哈希值。在这种情况下,来自%hash2的值在它们具有共同密钥时会替换%hash1中的值:
@hash1{ keys %hash2 } = values %hash2;
答案 2 :(得分:14)
这是一个老问题,但在我的Google搜索“perl merge hashes”中名列前茅 - 但它没有提到非常有用的CPAN模块Hash::Merge
答案 3 :(得分:5)
对于哈希引用。你应该使用如下的花括号:
$hash_ref1 = {%$hash_ref1, %$hash_ref2};
使用括号和不上面的建议答案:
$hash_ref1 = ($hash_ref1, $hash_ref2);