in reply to Re: Problem with a sort result
in thread Problem with a sort result

in fact, Perl does what we tell to do, and is difficult to spot some valid Perl code that was not what we intended,but it still compile.
The tricky part is that, contrarly to what i remembered, the sort sub must not returns -1 or 0 or +1, but:returns an integer less than, equal to, or greater than 0 so all the subtractions of octets are valid return value when choosing if $a or $b must be returned.

L*
There are no rules, there are no thumbs..
Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.

Replies are listed 'Best First'.
Re^3: Problem with a sort result
by anonymized user 468275 (Curate) on Jan 14, 2016 at 23:31 UTC
    The danger is there might be some kind of magic at work with $a, $b and the comparison operators that gets disrupted when going off book. In the case of the each function that is certainly the case.

    One world, one people

      Looks to me like it's an integer/bigint problem: 9 digits:
      perl -E' $h={foo=>{bar=>10000000000},baz=>{bar=>70000000},qux=>{bar=>2000000000 +0}}; say "$_: $h->{$_}->{bar}" for sort { eval { say $h->{$b}->{bar}. " - " +.$h->{$a}->{bar}." = ".($h->{$b}->{bar} - $h->{$a}->{bar}); $h->{$b}- +>{bar} - $h->{$a}->{bar} } } keys %$h; ' 10000000000 - 70000000 = 9930000000 20000000000 - 10000000000 = 10000000000 qux: 20000000000 foo: 10000000000 baz: 70000000
      the expected output is correct. 12 digits:
      perl -E' $h={foo=>{bar=>10000000000000},baz=>{bar=>70000000},qux=>{bar=>2000000 +0000000}}; say "$_: $h->{$_}->{bar}" for sort { eval { say $h->{$b}->{bar}. " - " +.$h->{$a}->{bar}." = ".($h->{$b}->{bar} - $h->{$a}->{bar}); $h->{$b}- +>{bar} - $h->{$a}->{bar} } } keys %$h; ' 20000000000000 - 70000000 = 19999930000000 10000000000000 - 70000000 = 9999930000000 foo: 10000000000000 baz: 70000000 qux: 20000000000000
      incorrect ordering.

      rdfield

        Infact it is something strange: while in motorbike this morning i thought i was wrong (in my previous post): the results of subtraction must be valid too when sorting: big minus less is greater than zero; equal minus equal is 0 and little minus big is less than zero:
        perl -e "print join qq(\n),sort {$a - $b} @ARGV" 33 1 2 99 1 2 33 99 # same result using <=> or -
        using big nums give me incorrect ordering using subtraction when one number is ten digits or more:
        perl -e "print join qq(\n),sort {$a - $b} @ARGV" 10000000000 3 2 10000000000 2 3


        L*
        There are no rules, there are no thumbs..
        Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.