foreach my $key1 ( sort { $hash2{$a}{key} cmp $hash2{$b}{key} || $a <=> $b } keys %hash1 ) {