How do I append hash a to hash b in Perl without using a loop?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If you mean take the union of their data, just do:
%c = (%a, %b);
回答2:
You can also use slices to merge one hash into another:
@a{keys %b} = values %b;
Note that items in %b will overwrite items in %a that have the same key.
回答3:
This will merge hashes and also take into account undefined entries, so they don't replace the content.
my %hash = merge(\%hash1, \%hash2, \%hash3);
sub merge {
my %result;
%result = %{ $_[0] };
shift;
foreach my $ref (@_) {
for my $key ( keys %{$ref} ) {
if ( defined $ref->{$key} ) {
$result{$key} = $ref->{$key};
}
}
}
return %result;
}
回答4:
my %c = %a;
map {$c{$_} = $b{$_}} keys %b;