for ($i = 0; $i < 50; $i++) { #loop over array of hashes (each subset will have 50 keys) foreach my $key (keys $subsets[$i]) { #5 keys at each level my $max = 0; my @max; for my $key1 (keys %distances) { if $key !exists (keys %used) { $max = max (values %{$distances{$key1}}); push @max, $max; # somehow retrieve the 2nd key } } my $maxmax = max @max; # $subsets[$i+1]{2nd_key_with_max_val} = "e.g. C1" # push %used with key and value @max = []; } }