循环遍历复杂的哈希结构
我有以下哈希结构 $chainStorage{$R1}{$S1}{$C1} = \@A1
$chainStorage = {
'ACB' => {
'E' => {'06' => [100, 200, 95]}
'B' => {'23' => [20, 1000, 05, 30]}
},
'AFG' => {
'C' => { '24' => [18, 23, 2300, 3456]}
},
'HJK' => {
'A' => {'12' => [24, 25, 3200, 5668]}
'D' => {'15' => [168]}
}
};
例如,ACB
对应两个数组,[100, 200, 95] 和
[20, 1000, 05, 30]
而 E
仅对应于 [100, 200, 95]
。
现在,我需要将数组中与第一级键(例如ACB
)相对应的所有元素添加在一起。
换句话说,在另一个哈希结构中,我想要 ACB
对应于
100+200+95 + 20+1000+05+30 = 1450
如何通过 $chainStorage
实现此功能?
I have the following hashed structure $chainStorage{$R1}{$S1}{$C1} = \@A1
$chainStorage = {
'ACB' => {
'E' => {'06' => [100, 200, 95]}
'B' => {'23' => [20, 1000, 05, 30]}
},
'AFG' => {
'C' => { '24' => [18, 23, 2300, 3456]}
},
'HJK' => {
'A' => {'12' => [24, 25, 3200, 5668]}
'D' => {'15' => [168]}
}
};
For example, ACB
corresponds to two arrays,[100, 200, 95]
and [20, 1000, 05, 30]
while E
corresponds to [100, 200, 95]
only.
Right now, I need to add all of the elements in the array corresponding to the first-level key, e.g., ACB
, together.
In other words, in another hash structure, I want ACB
corresponds to
100+200+95 + 20+1000+05+30 = 1450
How to implement this functionality over $chainStorage
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做:
输出:
You could do something like:
output:
您可以编写一个类似标准尾递归折叠 (+) 的例程,该例程提供 Perl 数据结构的任意层次结构的广度优先下降,对遇到的所有数值标量求和。示例:
我尚未测试此代码,但任何错误都应该很容易纠正。如果您想要正确的尾递归,您可能需要将最终返回行替换为:
最后,您可以
绑定
一个使用此函数的对象来动态提供您所需的类似哈希的接口。You could write a standard tail recursive
fold (+)
like routine that provides a breadth first descent of an arbitrary hierarchy of perl data structures, summing all numerical scalars encountered. Example :I have not tested this code, but any errors should be easy to correct. If you want proper tail recursion, you might need to replace the final return line by :
Finally, you could
tie
an object that employs this function to provide your desired interface hash-like dynamically.