sub cmp_undef { my ( $a, $b ) = @_; return $a cmp $b if defined $a and defined $b; return $b cmp $a; # invert order otherwise } @$ResultsFinal = sort \&cmp_undef(...,...), @$ResultsFinal;