in reply to Generate union of the two hashes

As I am a bum and want to simplify my answer, I'll treat $h1 and $h2 as %h1 and %h2 instead of refs to anon hashes.
Currently you have %h2 values overwriting the %h1 values, is that how you want your union to work?
You could merge the values where %h2 looks to see if there is a value for that key in %h1 and then merge those values accordingly
Also I presume you are doing something with the %h2 hash after merging in the %h1 data other than just printing right? If just printing, just skip the keys that exist in the hash that should have precedence if clobbering.

One suggestion to make your code more readable / maintainable is not to use reference as a variable name, perhaps (source, target as names instead?). Per Damien I name my references _ref so I know what they are when I read them.

Updated:
sub union_of_h1_h2 { my ($h1_ref, $h2_ref) = @_; my %output = %$h1_ref; for my $topkey (keys %{$h2_ref}) { for my $filename (keys %{$h2_ref{$topkey}}) { for my $bottomkey (keys %{$h2_ref{$topkey}{$filename}}) { $output{$topkey}{$filename}{$bottomkey} = $h2_ref->{$topkey +}{$filename}{$bottomkey} unless (Condition); } } } return \%output; }

I'm unclear what condition you want so I just left it there as Condition
Also might want to rename the keys there from (topkey,filename,bottomkey) to things that actually make sense to you.