Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Sorting data structure

by ioannis (Abbot)
on Oct 14, 2005 at 05:11 UTC ( #500126=note: print w/replies, xml ) Need Help??


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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://500126]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (5)
As of 2022-12-04 18:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?