How can I combine hashes in Perl?

后端 未结 4 924
天命终不由人
天命终不由人 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:09

    Quick Answer (TL;DR)

    
        %hash1 = (%hash1, %hash2)
    
        ## or else ...
    
        @hash1{keys %hash2} = values %hash2;
    
        ## or with references ...
    
        $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
    
    

    Overview

    • Context: Perl 5.x
    • Problem: The user wishes to merge two hashes1 into a single variable

    Solution

    • use the syntax above for simple variables
    • use Hash::Merge for complex nested variables

    Pitfalls

    • What do to when both hashes contain one or more duplicate keys
      • (see e.g., Perl - Merge hash containing duplicate keys)
      • (see e.g, Perl hashes: how to deal with duplicate keys and get possible pair)
    • Should a key-value pair with an empty value ever overwrite a key-value pair with a non-empty value?
      • What constitutes an empty vs non-empty value in the first place? (eg. undef, zero, empty string, false, falsy ...)

    See also

    • PM post on merging hashes
    • PM Categorical Q&A hash union
    • Perl Cookbook 5.10. Merging Hashes
    • websearch://perlfaq "merge two hashes"
    • websearch://perl merge hash
    • https://metacpan.org/pod/Hash::Merge

    Footnotes

    1 * (aka associative-array, aka dictionary)

提交回复
热议问题