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

perlnovice1 has asked for the wisdom of the Perl Monks concerning the following question:

hail esteemed monks,

thanks in advance for any help you can give me. this is a pretty basic question but i'm having real trouble with it. i have a list of hashes and i need to sort on one of the numerical elements of the hashes. so given a data structure like this:

my $data = [ {name => 'Oranges', order => 5}, {name => 'Apples', order => 3}, {name => 'Grapes', order => 7}, {name => 'Pears', order => 4}, ];

i need to re-sequence the data in the structure into numerical order based on the order attribute. i'm at a loss as to how to go about this. any help much appreciated!

Edit: g0n - code tags and formatting

Replies are listed 'Best First'.
Re: sorting a list of hashes on an element/attribute of the hash
by derby (Abbot) on Jun 04, 2007 at 13:57 UTC

    my $data = [ { name => 'Oranges', order => 5 }, { name => 'Apples', order => 3 }, { name => 'Grapes', order => 7 }, { name => 'Pears', order => 4 }, ]; my @newdata = sort { $a->{order} <=> $b->{order} } @$data;
    Check out perlfaq4 for more details on sorting hashes by values.

    -derby
Re: sorting a list of hashes on an element/attribute of the hash
by vrk (Chaplain) on Jun 04, 2007 at 13:59 UTC

    There are a few ways, but here's one:

    @$data = sort { $a->{order} <=> $b->{order} } @$data;

    --
    print "Just Another Perl Adept\n";

Re: sorting a list of hashes on an element/attribute of the hash
by princepawn (Parson) on Jun 04, 2007 at 17:04 UTC
    For small data sets, the answers given are readable and to the point. However, Sort::Key is just as readable and the fastest Perl sorting solution --- ideal if you have a large data set:
    use Sort::Key ; # sorting by a numeric integer key: @by_order = ikeysort { $_->{order} } @$data;


    Carter's compass: I know I'm on the right track when by deleting something, I'm adding functionality
      Well, I am currently working on Sort::Key::Radix that uses a Radix Sort as the sorting algorithm and has identical usage to Sort::Key.

      When sorting large data sets and for some kinds of data, as for instance small numbers (as shown on the OP), it can be much faster than Sort::Key.

      use Sort::Key::Radix qw(ukeysort); my @by_order = ukeysort { $_->{order} } @data;

      ...though I am still getting some FAIL reports from the CPAN testers.