HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Treat undef in Perl's <=> operator as +inf instead of 0

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
operatorperlinfundefinsteadtreat

Problem

I have to sort some numbers with Perl. But some of the numbers are undefined. Perl's compare operator ` treats undef as -inf 0. The result is, that the undefined numbers are at the beginning:

perl -MData::Dumper -e 'print Dumper(sort {$a  $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  $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?

Solution

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')  ($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')

Code Snippets

sort { ($a // 'Inf') <=> ($b // 'Inf') } 3, undef, 2, 1
(defined $a ? $a : 'Inf')

Context

StackExchange Code Review Q#106833, answer score: 5

Revisions (0)

No revisions yet.