develooper Front page | perl.perl5.porters | Postings from October 2011

[perl #94390] Inconsistent NaN sorting

Thread Next
From:
Father Chrysostomos via RT
Date:
October 12, 2011 23:30
Subject:
[perl #94390] Inconsistent NaN sorting
Message ID:
rt-3.6.HEAD-31297-1318487394-106.94390-15-0@perl.org
On Fri Jul 08 13:31:48 2011, alex@chmrr.net wrote:
> 
> This is a bug report for perl from alex@chmrr.net,
> generated with the help of perlbug 1.35 running under perl v5.8.8.
> 
> 
> -----------------------------------------------------------------
> [Please enter your report here]
> 
> Sorting a list containing NaN leads to odd results:
> 
>     umgah ~ $ perl -wle 'print for sort {$a <=> $b}
>    (4,6,5,2,NaN,3,1);'
>     2
>     4
>     5
>     6
>     NaN
>     1
>     3
> 
> Given that NaN, and repeated comparisons to it, is involved, this in
> itself is not terribly surprising.  However, `perldoc -f sort` says on
> the topic:
> 
>     Because "<=>" returns "undef" when either operand is "NaN"
>     (not-a-number), and because "sort" will trigger a fatal error
>     unless the result of a comparison is defined, when sorting with a
>     comparison function like "$a <=> $b", be careful about lists that
>     might contain a "NaN".
> 
> The promised fatal error does not seem to have appeared.  It is
> unclear if this is to be considered an error in the documentation, or
> a regression in the implementation of "sort."

The behaviour of sort with regard to undefined values return from
comparison routines changed intentionally in 5.12 (see bug #69384), but
the documentation was never updated.  Now it does not die, but produced
an ‘Uninitialized value’ warning for undef, for consistency with other
functions and operators that take numbers.

In previous perl versions, the {$a <=> $b} case is specially optimised
and the optimisation did not take undefs into account (presumably
because the implementor did not think it could happen).  It dies with
something more complex, like {($a)[0] <=> $b}, which is not optimised away.

I have just updated the documentation with commit 1bd4e8e32.

However, there is still an optimisation bug:

$ perl5.12.0 -wle 'print for sort {($a)[0] <=> $b} (4,6,5,2,NaN,3,1);'
Use of uninitialized value at -e line 1.
Use of uninitialized value at -e line 1.
Use of uninitialized value at -e line 1.
Use of uninitialized value at -e line 1.
Use of uninitialized value at -e line 1.
Use of uninitialized value at -e line 1.
2
4
5
6
NaN
1
3
$ perl5.12.0 -wle 'print for sort {$a <=> $b} (4,6,5,2,NaN,3,1);'
2
4
5
6
NaN
1
3

I’ve just fixed that with commit f3dab52a5.


Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About