我有以下哈希结构$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
上实现此功能? 最佳答案
您可以执行以下操作:
#!/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/