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

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

问题描述

将两个散列组合成 %hash1 的最佳方法是什么?我一直都知道 %hash2 和 %hash1 总是有唯一的键.如果可能的话,我也更喜欢一行代码.

$hash1{'1'} = 'red';$hash1{'2'} = '蓝色';$hash2{'3'} = '绿色';$hash2{'4'} = '黄色';

解决方案

Quick Answer (TL;DR)

<前>%hash1 = (%hash1, %hash2)## 要不然 ...@hash1{keys %hash2} = 值 %hash2;## 或参考...$hash_ref1 = { %$hash_ref1, %$hash_ref2 };

概述

  • 上下文:Perl 5.x
  • 问题:用户希望将两个哈希值1合并为一个变量

解决方案

  • 对简单变量使用上述语法
  • 对复杂的嵌套变量使用 Hash::Merge

陷阱

另见


脚注

1 *(又名 associative-array,又名 字典)

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

解决方案

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

See also


Footnotes

1 * (aka associative-array, aka dictionary)

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

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