http://qs321.pair.com?node_id=500126


in reply to Sorting data structure

The variable users, as used in the original post, represents a hash, not an array. This we know from the brace after the -> infix operator; therefore, assuming numerical comparison, the answer to the original question is this:
@users = sort { $::a->{count} <=> $::b->{count} } @users;
I favor the addition of :: to ensure that $a and $b remain global. This would have made a difference if the comparison was performed using the greater operator, >, and $a was lexical. For example, this will not work:
my $a = 'john'; @users = sort { $a->{count} > $b->{count} } @users;

Replies are listed 'Best First'.
Re^2: Sorting data structure
by davido (Cardinal) on Oct 14, 2005 at 05:52 UTC

    users is a hash, and we know this because of the brackets following $users: $users{$value}->{count}, as demonstrated in the original question.

    Based on what the OP told us, the structure could minimally look something like this:

    %users = ( john => { count => 1 }, frank => { count => 3 } );

    If the goal is to sort the list of users based on the value of count, you're not really doing that. You're jumping to the assumption that the datastructure looks more like this:

    @users = [ { count => 1 }, { count => 3 } ];

    In other words, your solution assumes that @users is an array of hashrefs, as opposed to being a hash at its top level. I don't see how you're deriving that assumption based on the original question.

    What your solution accomplishes is to sort the array, @users, based on $users->{count}, not based on $users{$value}->{count}.

    Another perplexing topic covered in your reply is that of using '>' as the comparison operator within a sort routine. sort expects a comparison that returns either -1, 0, or 1. cmp does this, as does <=>. But there is nothing that will cause the '>' (greater than) operator to return a -1. So you're correct that "this won't work", but it has nothing to do with your choice of $::a and $::b versus $a and $b, and everything to do with an inappropriate use of the '>' operator. sort always uses a package global version of $a and $b anyway.


    Dave

    A reply falls below the community's threshold of quality. You may see it by logging in.