in reply to Re: sorting hash ref
in thread sorting hash ref

reverse sort { my_cmp($a, $b) } @foo # (1)
and
sort { my_cmp($b, $a) } @foo # (2)
are not strictly equivalent: order is reversed for terms comparing as equal.

For instance:

@u = map { [$_, $i++] } (0,0,3,2,2); $" = '-'; print( (map {$_->[1]} reverse sort { $a->[0] <=> $b->[0] } @u), "\n", (map {$_->[1]} sort { $b->[0] <=> $a->[0] } @u), "\n" );
prints
24310 23401
though I believe that most of the times, the correct solution is actually the second one or it just doesn't mind at all!

Replies are listed 'Best First'.
Re^3: sorting hash ref
by halley (Prior) on Jun 10, 2005 at 14:59 UTC
    Your assertion about stable sort ordering is true, though I'd add that you cannot depend on ANY sort order when iterating through the keys of a normal hash.

    Even two successive runs using the same hash full of data may give different ordering, since (1) it may be influenced by insertion order, and (2) it may be influenced by insertion attack protections, and (3) it may be influenced by other changes in the algorithms between versions of perl.

    --
    [ e d @ h a l l e y . c c ]