in reply to Sorting Puzzle

Your "numbers" don't appear to be variable-width so just sort w/o specifying any comparison routine and you'll get the desired order:

foreach $j ( sort keys %test ) {

Others have pointed out that your numbers are too big for accurate numeric comparisons in Perl. The notes about avoiding the quotes or hash keys being strings and having to use "0+" to force numeric interpretation make no sense to me, however. $a <=> $b already forces $a and $b to be interpretted as numbers, always.

Your numbers require about 91 bits and Perl usually uses about 53 bits of mantissa for floating point numbers so numeric comparison on these values end up comparing truncated values like 2007030110300020000000000000 instead.

- tye        

Replies are listed 'Best First'.
Re^2: Sorting Puzzle (just sort)
by imp (Priest) on Feb 20, 2007 at 22:26 UTC
    $a <=> $b already forces $a and $b to be interpretted as numbers, always.
    It doesn't appear to with perl 5.8.2:
    use strict; use warnings; my $d1 = '2007030110300020070301133000'; my $d2 = '2007030110300020070301143000'; printf "plain = %d\n", ($d1 <=> $d2); { use bigint; printf "bigint = %d\n", ($d1 <=> $d2); } { use bigint; printf "bigint-0 = %d\n", (($d1 -0)<=> ($d2-0)); }
    Output:
    plain = 0 bigint = 0 bigint-0 = -1

      That doesn't show $d1 and $d2 being compared as not numbers and so doesn't contradict my point. I guess the other points are about getting bigint to magically turn numeric expressions into objects. I'm not a fan of such subtle magic and so didn't recommend the use of bigint.pm and see no real value for it here anyway. But thanks for indirectly clarifying those points.

      - tye        

Re^2: Sorting Puzzle (just sort)
by jdporter (Paladin) on Feb 20, 2007 at 22:51 UTC
    The notes about ... having to use "0+" to force numeric interpretation make no sense to me

    I'm not saying it makes sense to me, either. But the perl interpreter don't lie, if you get my drift. You have to do both things (use bigint and manually coerce the numeric conversion) for the numeric comparison to work properly. Try it yourself if you don't believe me.

    This is perl, v5.8.8 built for MSWin32-x86-multi-thread
    
    Binary build 819 [267479] provided by ActiveState 
    Built Aug 29 2006 12:42:41
    
    A word spoken in Mind will reach its own level, in the objective world, by its own weight
      Tye's statement was correct. Perl does indeed compare the two values numerically, but the magic of bigint is not triggered. The 0+ doesn't force numeric comparison in this case, it triggers bigint magic.
      A reply falls below the community's threshold of quality. You may see it by logging in.
      But why would you recommend bigint rather than Math::BigInt in this case???

        I have no reason; I grabbed the first one I found. If other "big math" modules work as well, great!