for (keys %$start) { my @all = ($_, keys %{$start->{$_}}); my $processed; for my $setref (@$end) { my (@found, @not_found); for my $item (@all) { push @found, grep {$item eq $_} @$setref; } if (@found) { for my $item (@all) { push @not_found, $item unless grep {$item eq $_} @found; } push @$setref, @not_found if @not_found; $processed++; } } push @$end, [ @all ] unless $processed; } #### my $start = { a => {b => 1}, c => {d => 2}, d => {a => 1} };