in reply to Problem with a sort result

Hello kzwiz,

Personally I've never seen `-` used as the comparison operator in a custom sort. This doesn't mean anything other than I've never seen it, but I do find the standard numerical comparison operator (`<=>`) provides your expected results:

$ perl -E' $h={foo=>{bar=>13908480193},baz=>{bar=>771918754},qux=>{bar=>288170793 +399}}; say "$_: $h->{$_}->{bar}" for sort { $h->{$b}->{bar} - $h->{$a}->{bar} + } keys %$h; ' foo: 13908480193 baz: 771918754 qux: 288170793399
$ perl -E' $h={foo=>{bar=>13908480193},baz=>{bar=>771918754},qux=>{bar=>288170793 +399}}; say "$_: $h->{$_}->{bar}" for sort { $h->{$b}->{bar} <=> $h->{$a}->{ba +r} } keys %$h; ' qux: 288170793399 foo: 13908480193 baz: 771918754
Hope this helps!


The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Problem with a sort result
by Discipulus (Canon) on Jan 14, 2016 at 17:57 UTC
    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.
      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