How can I join two hashes in Perl without using a

2019-06-15 11:12发布

How do I append hash a to hash b in Perl without using a loop?

标签: perl hash
4条回答
混吃等死
2楼-- · 2019-06-15 11:18

If you mean take the union of their data, just do:

%c = (%a, %b);
查看更多
看我几分像从前
3楼-- · 2019-06-15 11:21

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;
}
查看更多
We Are One
4楼-- · 2019-06-15 11:23

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.

查看更多
仙女界的扛把子
5楼-- · 2019-06-15 11:39
my %c = %a;
map {$c{$_} = $b{$_}} keys %b;
查看更多
登录 后发表回答