gpt4 book ai didi

perl - 遍历复杂的哈希结构

转载 作者:行者123 更新时间:2023-12-04 01:22:52 24 4
gpt4 key购买 nike

我有以下散列结构 $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)对应的所有元素加在一起。

也就是说,在另外一个hash结构中,我要ACB对应

100+200+95 + 20+1000+05+30 = 1450

如何通过$chainStorage实现这个功能?

最佳答案

你可以这样做:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dump qw(dump);

my $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]}
}
};


while (my($k,$v) = each %$chainStorage) {
my $sum = 0;
while (my($k2,$v2) = each%$v) {
while (my($k3,$v3) = each %$v2) {
foreach (@$v3) {
$sum += $_;
}
}
}
$chainStorage->{$k} = $sum;
}
dump$chainStorage;

输出:

{ ACB => 1450, AFG => 5797, HJK => 9085 }

关于perl - 遍历复杂的哈希结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8617147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com