How can I combine hashes in Perl?

后端 未结 4 923
天命终不由人
天命终不由人 2020-11-29 00:29

What is the best way to combine both hashes into %hash1? I always know that %hash2 and %hash1 always have unique keys. I would also prefer a single line of code if possibl

4条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 01:02

    Check out perlfaq4: How do I merge two hashes. There is a lot of good information already in the Perl documentation and you can have it right away rather than waiting for someone else to answer it. :)


    Before you decide to merge two hashes, you have to decide what to do if both hashes contain keys that are the same and if you want to leave the original hashes as they were.

    If you want to preserve the original hashes, copy one hash (%hash1) to a new hash (%new_hash), then add the keys from the other hash (%hash2 to the new hash. Checking that the key already exists in %new_hash gives you a chance to decide what to do with the duplicates:

    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};
            }
        }
    

    If you don't want to create a new hash, you can still use this looping technique; just change the %new_hash to %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};
            }
        }
    

    If you don't care that one hash overwrites keys and values from the other, you could just use a hash slice to add one hash to another. In this case, values from %hash2 replace values from %hash1 when they have keys in common:

    @hash1{ keys %hash2 } = values %hash2;
    

提交回复
热议问题