How can I join two hashes in Perl without using a

2019-06-15 11:00发布

问题:

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;


标签: perl hash