in reply to sorting scientific numbers

Chances are good that by virtue of how the numeric data is getting into your script, Perl is seeing '1e-13' as a string, not a number. You can see this happening here:

perl -e "print q/2e+11/, $/; print 2e+11, $/;"

You can coerce it back to a number by treating it like one. One way is by adding zero to it:

perl -e "print q/2e+11/ + 0, $/;"

And here is that theory applied to an example that may more closely resemble your problem code.

my @numbers; while( my $num = <DATA> ) { chomp $num; push @numbers, $num + 0; } print "$_\n" for sort { $a <=> $b } @numbers; __DATA__ 1e-13 2e-18 1e-11

I hope this is on the right track. ;)


Dave

Replies are listed 'Best First'.
Re^2: sorting scientific numbers
by kaif (Friar) on Jun 08, 2005 at 07:57 UTC

    That's a good theory, but the spaceship operator $a <=> $b coerces its argument into integers numbers, so this shouldn't matter. Indeed, run your code without the + 0 or simply

    perl -le'$,="\n"; print sort {$a<=>$b} qw(1e-13 2e-18 1e-11)'
    and you will see that the output is the same.

Re^2: sorting scientific numbers
by tlm (Prior) on Jun 08, 2005 at 12:31 UTC

    This is somewhat tangetial, but in a numerical context perl will coerce any string that begins with something recognizable as a number into a number. That's why "0 but true" is a perfectly good1 "true zero." See Is '2x' + '3y' == 5 documented? and the man page for the C atof function.

    1Well, not quite. As it turns out '0 but true' has a "special dispensation" that disables the warnings that perl would have otherwise have generated. E.g.:
    % perl -wle 'print "OK" if "0 but true" < 1' OK % perl -wle 'print "OK" if "0 but righteous" < 1' Argument "0 but righteous" isn't numeric in numeric lt (<) at -e line +1. OK

    the lowliest monk