#!/usr/bin/perl # https://perlmonks.org/?node_id=1228412 use strict; use warnings; my $one = { data => { dir1 => { fileA => { pid => { 61781 => 1 }, total => 13 }, fileB => { pid => { 61799 => 1 }, total => 12 }, }, dir2 => { fileA => { pid => { 61439 => 1 }, total => 5 }, fileC => { pid => { 12345 => 1 }, total => 10 }, }, }, total => { fileA => 18, fileB => 12, fileC => 10 }, }; my $two = { data => { dir3 => { fileA => { pid => { 616161 => 1 }, total => 6 }, fileD => { pid => { 54321 => 1 }, total => 12 }, }, dir4 => { fileA => { pid => { 1718 => 1 }, total => 2 }, fileE => { pid => { 15151 => 1 }, total => 3 }, }, }, total => { fileA => 8, fileD => 12, fileE => 3 }, }; sub combinemanyhashes { my $newhash = { data => { map %{ $_->{data} // {} }, @_ }, total => do { my %total; for my $href ( @_ ) { $total{$_} += $href->{total}{$_} for keys %{ $href->{total} // {} }; } \%total; } }; return $newhash; } my $totalhashref = {}; $totalhashref = combinemanyhashes( $totalhashref, $one, $two ); use Data::Dump 'dd'; dd $totalhashref;