Treat undef in Perl's  operator as +inf instead of 0 I have to sort some numbers with Perl. But some of the numbers are undefined. Perl's compare operator &lt;=&gt; treats undef as -inf 0. The result is, that the undefined numbers are at the beginning:

perl -MData::Dumper -e 'print Dumper(sort {$a &lt;=&gt; $b} 3, undef, 2, 1);'
$VAR1 = undef;
$VAR2 = 1;
$VAR3 = 2;
$VAR4 = 3;


I want them to occur at the end, because they represent new items, which should be added at the end. This means I am looking for a way to change the way Perl treats undef. In my case undef should be treated as +inf instead of -inf 0. I came up with the following expression.

($a &lt;=&gt; $b) * ((defined $a)*2-1) * ((defined $b)*2-1)


Is it always correct or did I miss anything?

And is there an easier way to achieve the same?
In fact, Perl treats undef as 0 in numeric contexts, and warns about that (why there's no -w in your one-liner?). You can use the defined-or operator to handle it:

sort { ($a // 'Inf') &lt;=&gt; ($b // 'Inf') } 3, undef, 2, 1


You need Perl v5.10+ for it to work, in older versions, you have to be more verbose:

(defined $a ? $a : 'Inf')