【发布时间】:2010-09-25 21:18:20
【问题描述】:
将两个哈希组合成 %hash1 的最佳方法是什么?我一直都知道 %hash2 和 %hash1 总是有唯一的键。如果可能的话,我也更喜欢一行代码。
$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';
【问题讨论】:
标签: perl dictionary hash merge
将两个哈希组合成 %hash1 的最佳方法是什么?我一直都知道 %hash2 和 %hash1 总是有唯一的键。如果可能的话,我也更喜欢一行代码。
$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';
【问题讨论】:
标签: perl dictionary hash merge
undef,零,空字符串,false,falsy ...)1 *(又名associative-array,又名dictionary)
【讨论】:
%hash1 = (%hash1, %hash2)
$hash_ref1 设置为$hash_ref2,不会合并。你想要$hash_ref1 = { %$hash_ref1, %$hash_ref2 };,我会编辑答案。
查看perlfaq4: How do I merge two hashes。 Perl 文档中已经有很多很好的信息,您可以立即获得,而不必等待其他人回答。 :)
在您决定合并两个散列之前,您必须决定如果两个散列包含相同的键,并且您想保留原来的散列,该怎么做。
如果要保留原始散列,请将一个散列 (%hash1) 复制到新散列 (%new_hash),然后将另一个散列 (%hash2) 中的键添加到新散列中。检查该键是否已存在in %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);
【讨论】: