如何在不使用循环的情况下在Perl中连接两个哈希?

时间:2022-08-04 07:27:59

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

如何在不使用循环的情况下将散列a附加到Perl中的散列b?

4 个解决方案

#1


31  

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

如果你的意思是采用他们的数据联合,只需:

%c = (%a, %b);

#2


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.

请注意,%b中的项目将覆盖%a中具有相同键的项目。

#3


2  

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


2  

my %c = %a;
map {$c{$_} = $b{$_}} keys %b;

#1


31  

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

如果你的意思是采用他们的数据联合,只需:

%c = (%a, %b);

#2


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.

请注意,%b中的项目将覆盖%a中具有相同键的项目。

#3


2  

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


2  

my %c = %a;
map {$c{$_} = $b{$_}} keys %b;