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

I have the following code:
# fetch data from sql while (my $row = $res->fetchrow_hashref()) { my %rowdata; # $score is generated by some badass algoritms, and is an integer $rowdata{SCORE} = $score; $rowdata{ID} = $row->{id}; $rowdata{TITLE} = $row->{title}; push (@output, \%rowdata); }

This code gives me an array (oh yes, working) and everything is fine.

But how can I order @output by the $rowdata{SCORE} value? I want the highest integer to be listed first (descending).

I have tried with different sortings methods, but nothing is working. Could anybody help me out?

- grath

Replies are listed 'Best First'.
Re: Sorting array
by dragonchild (Archbishop) on Jun 14, 2004 at 03:05 UTC
    my @sorted_rows = sort { $b->{SCORE} <=> $a->{SCORE} } @output;

    ------
    We are the carpenters and bricklayers of the Information Age.

    Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

    I shouldn't have to say this, but any code, unless otherwise stated, is untested

Re: Sorting array
by thor (Priest) on Jun 14, 2004 at 03:32 UTC
    The perl answer has been provided. However, there is an SQL answer here as well. You're pulling your data from a database. Why not put an order by clause on your select? This is almost certainly going to be more efficient for your program.

    thor

      Maybe, if you can guarantee you want to sort by a value that's coming from your database. If you want to allow the user to specify the column to sort on and you create columns that are derivatives (such as percentages), then you have to sort in Perl.

      Oh - and sorting in Perl can occasionally be more efficient than sorting in the database. The reason is that, depending on the implementation, the database will sort by copying the values from one section of memory to another. Perl sorts by moving pointers around. With larger datasets, Perl's way could be faster.

      ------
      We are the carpenters and bricklayers of the Information Age.

      Then there are Damian modules.... *sigh* ... that's not about being less-lazy -- that's about being on some really good drugs -- you know, there is no spoon. - flyingmoose

      I shouldn't have to say this, but any code, unless otherwise stated, is untested

Re: Sorting array
by Zaxo (Archbishop) on Jun 14, 2004 at 03:08 UTC

    Here, @output = sort {$b->{SCORE} <=> $a->{SCORE}} @output; Each element of @output is a reference to a hash, and it can be dereferenced to get its data. Placing $b on the left of the comparison makes the sort descending.

    After Compline,
    Zaxo

Re: Sorting array
by Anonymous Monk on Jun 14, 2004 at 03:07 UTC
    Thanks dude :)