Strange kind behavior

I have this piece of script:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @arr = ( { name => 'foo', value => 123, }, { name => 'bar', value => 'nan', }, { name => 'foobar', value => 456, }, ); @arr = sort {$a->{value} <=> $b->{value} } @arr; print Dumper(\@arr); 

I have no problem in Windows XP / Strawberry Perl 5.10.1

either Linux 2.6.12-1 i386 / Perl v5.8.5, built for i386-linux-thread-multi,

but on Linux 2.6.18-53 / Perl v5.8.8 for x86_64-linux-thread-multi, I got the error message:

 Sort subroutine didn't return a numeric value at testsort.pl line 21. 

What is going wrong and how can I fix it?

+7
sorting perl
source share
2 answers

In some assemblies, "nan" is forced to the number 0 for comparison <=> , and sorting succeeds. In the other lines, nan treated as "not a number", and the return value from <=> is undefined.

For maximum portability, check the value for a good number:

( isnan routine from How do I create or check for NaN or infinity in Perl? ):

 sub isnan { ! defined( $_[0] <=> 9**9**9 ) } @arr = sort { isnan($a->{value}) ? 0 : $a->{value} <=> isnan($b->{value}) ? 0 : $b->{value} } @arr; 
+6
source share

2 Solutions

  • mobrule solution:

     sub isnan { ! defined( $_[0] <=> 9**9**9 ) } @arr = sort { isnan($a->{value}) ? 0 : $a->{value} <=> isnan($b->{value}) ? 0 : $b->{value} } @arr; 
  • Perldoc solution:

     @result = sort { $a <=> $b } grep { $_ == $_ } @input; 

  • Gives the value NaN a 0 , which should insert it at the top of the list.
  • Uses NaN != NaN to exclude any NaN from the input list.

As mobrule pointed out , this is caused by comparing NaN between assemblies.

+4
source share

All Articles