将两个散列组合成 %hash1 的最佳方法是什么?我一直都知道 %hash2 和 %hash1 总是有唯一的键。如果可能的话,我也更喜欢一行代码。
$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';
将两个散列组合成 %hash1 的最佳方法是什么?我一直都知道 %hash2 和 %hash1 总是有唯一的键。如果可能的话,我也更喜欢一行代码。
$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';
%hash1 = (%hash1, %hash2) ## 要不然 ... @hash1{keys %hash2} = 值 %hash2; ## 或带有引用... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
undef
,零,空字符串false
,,假...)查看perlfaq4:如何合并两个哈希。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;
这是一个老问题,但在我的 Google 搜索“perl 合并哈希”中排名很高——但它没有提到非常有用的 CPAN 模块Hash::Merge
对于哈希引用。您应该使用如下花括号:
$hash_ref1 = {%$hash_ref1, %$hash_ref2};
而不是上面使用括号的建议答案:
$hash_ref1 = ($hash_ref1, $hash_ref2);