大家好我试图使用相同的密钥从多个哈希中添加多个值。
这是我想要的计划的结果。
HASH1 => {
'2016-07-01' => { 'val1' => '7', 'val2' => '9', },
'2016-07-02' => { 'val1' => '10', 'val2' => '6', } }
HASH2 => {
'2016-07-01' => { 'val1' => '8', 'val2' => '4', },
'2016-07-03' => { 'val1' => '3', 'val2' => '2', } }
HASH3 => {
'2016-07-01' => { 'val1' => '6', 'val2' => '5', },
'2016-07-02' => { 'val1' => '1', 'val2' => '2', },
'2016-07-04' => { 'val1' => '4', 'val2' => '2', } }
OUTPUT HASH => {
'2016-07-01' => { 'val1' => '21', 'val2' => '18', },
'2016-07-02' => { 'val1' => '11', 'val2' => '8', },
'2016-07-03' => { 'val1' => '3', 'val2' => '2', },
'2016-07-04' => { 'val1' => '4', 'val2' => '2', }, }
我尝试将重复键推送到数组以识别每个键,然后添加值。 我尝试的是比较2哈希,但我想让它为多个哈希值。
my @common = ();
foreach (keys %HASH1) {
push(@common, $_) if exists $HASH2{$_};
}
foreach my $DUP_KEY (@common){
my $v1 = $HASH1{$DUP_KEY}{'val1'} + $HASH2{$DUP_KEY}{'val1'};
my $v2 = $HASH1{$DUP_KEY}{'val2'} + $HASH2{$DUP_KEY}{'val2'};
$HASH1{$DUP_KEY}{'val1'} = $v1;
$HASH1{$DUP_KEY}{'val2'} = $v2;
}
my %OUT_HASH = (%HASH1, %HASH2);
foreach my $key (keys %OUT_HASH) {push(@ARR, $key);}
foreach (sort @ARR) {push(@ARR_CLEAN, $_);
}
但结果并不像预期的那样,因为我只获得了重复的密钥。
有人愿意帮助我吗?谢谢!答案 0 :(得分:2)
总结哈希的哈希值,遍历所有哈希值,遍历第一个键(此处为日期),然后遍历第二个键(此处为值)。在新哈希中总结数字。
为了清楚起见,我会移动代码将值加到自己的子上,然后传递你想要总结的哈希的引用。
use strict;
use warnings;
sub sum {
my %sums;
foreach my $hash (@_) {
foreach my $date (keys %{$hash}) {
foreach my $val (keys %{$$hash{$date}}) {
$sums{$date}{$val} += $$hash{$date}{$val};
}
}
}
return %sums;
}
my %HASH1 = (
'2016-07-01' => {'val1' => '7', 'val2' => '9'},
'2016-07-02' => {'val1' => '10', 'val2' => '6'}
);
my %HASH2 = (
'2016-07-01' => {'val1' => '8', 'val2' => '4'},
'2016-07-03' => {'val1' => '3', 'val2' => '2'}
);
my %HASH3 = (
'2016-07-01' => {'val1' => '6', 'val2' => '5'},
'2016-07-02' => {'val1' => '1', 'val2' => '6'},
'2016-07-04' => {'val1' => '4', 'val2' => '2'}
);
my %sums = sum(\%HASH1, \%HASH2, \%HASH3);
foreach my $date (sort keys %sums) {
print "$date\n";
foreach my $val (keys %{$sums{$date}}) {
print " $val: $sums{$date}{$val}\n";
}
}