如何在Perl中组合散列? [英] How can I combine hashes in Perl?

查看:150
本文介绍了如何在Perl中组合散列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将两个哈希值组合到%hash1中的最佳方法是什么?我总是知道%hash2和%hash1总是有唯一的键。如果可能,我也会喜欢一行代码。

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 possible.

$hash1{'1'} = 'red';
$hash1{'2'} = 'blue';
$hash2{'3'} = 'green';
$hash2{'4'} = 'yellow';


推荐答案

快速回答(TL; DR)



Quick Answer (TL;DR)



    %newHash = (%hash1, %hash2); %hash1 = %newHash;

    ## or else ...

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

    ## or else ...

    %hash1 = (%hash1, %hash2)

    ## or with references ... (per http://stackoverflow.com/users/196507/lepe)

    $hash_ref1 = ($hash_ref1, $hash_ref2);



概述




  • strong>上下文: Perl 5.x

  • 问题:用户希望将两个散列 1 合并到一个变量

  • Overview

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

      • 以上简单变量

      • 使用Hash ::合并复杂的嵌套变量


      • 当两个哈希值包含一个或多个重复键时,该怎么办?


        • 一个带有空值的键值对是否会覆盖一个非空值的键值对?

        • (注意:原来的问题排除了这种情况,但它是一个重要的一个)

        • 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

        1 *(又名关联数组,又名 dictionary

        这篇关于如何在Perl中组合散列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆