use List::Util qw( sum ); my %cache; my @keys = keys %$hash_ref; foreach my $a_ (@{ $array_ref }) { my $i = 0; foreach my $b_ (split('-', $a_)) { $i += $cache{$b_} //= sum map { $_->{value} } @{ $foo->{$b_} }{@keys}; # Use the cached value or compute the sum } push @{ $bar->{$i} }, $a_; }