如何在 Perl 中组合哈希? [英] How can I combine hashes in Perl?
本文介绍了如何在 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
陷阱
- 当两个散列都包含一个或多个重复键时怎么办
- (参见例如,Perl - 合并包含重复键的哈希)
- (参见例如,Perl 哈希:如何处理重复键并获得可能的配对)
- 具有空值的键值对是否应该覆盖具有非空值的键值对?
- 首先是什么构成空值与非空值?(例如
undef
、零、空字符串、false
、falsy ...)
- 首先是什么构成空值与非空值?(例如
另见
- 关于合并哈希的 PM 帖子
- PM 分类问答哈希联合
- Perl Cookbook 5.10.合并哈希
- websearch://perlfaq合并两个哈希"
- websearch://perl 合并哈希
- https://metacpan.org/pod/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
- What do to when both hashes contain one or more duplicate keys
- 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? (e.g.
undef
, zero, empty string,false
, falsy ...)
- What constitutes an empty vs non-empty value in the first place? (e.g.
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)
这篇关于如何在 Perl 中组合哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文