in reply to Sort array according to a value in each element?

A GRT will do it.

#! perl -slw use strict; my @array = split '\n', <<'EOA'; Item1 - 2 foo, 2 bar Item2 - 0 foo, 1 bar Item3 - 1 foo, 3 bar Item4 - 1 foo, 2 bar EOA my @sorted = map{ substr $_, 5; } sort map{ sprintf '%05d%s', $_ =~ m[,\s+(\d+)], $_; } @array; print for @sorted; __END__ Item2 - 0 foo, 1 bar Item1 - 2 foo, 2 bar Item4 - 1 foo, 2 bar Item3 - 1 foo, 3 bar

Update: Limbic~Region pointed out that you wanted descending not ascending. so substitute sort { $b cmp $a } for  sort or use reverse on the results.


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail

Replies are listed 'Best First'.
Re: Re: Sort array according to a value in each element?
by McMahon (Chaplain) on May 24, 2004 at 18:44 UTC
    I gotta like two working solutions with examples demonstrating the Schwartzian Transform and Guttman Rosler Transform...

    Now, having hardly any background in Computer Science-- bubble sorts are about my speed =)-- I have to woodshed for a while to figure out *why* they work-- and how to clean up a couple of warnings.

    Thanks L~R and BrowserUK!
      This Q&A might help enlighten you on how they work. They're not sort algorithms like bubblesort, they just manipulate the data so that the sort comparison looks at the right thing. The Schwartzian transform is explained there. The GRT just prefixes the data with the sorting information, then strips it off at the end. Essentially, it's a Schwartzian using a scalar as the array.

      The PerlMonk tr/// Advocate