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

Often I have wanted to be able to sort on some sort of computed or complex value. I know map is useful to do this sort of thing. How would I for instance sort an array by the product of the second and third columns. The columns for each entry in the array are space delimited. I also want to compute the value I am sorting only once per entry in my array.
For example:
$array[0]="25 3 7"; #computed value 3*7=21 $array[1]="68 4 6"; #computed value 4*6=24; $array[2]="23 2 3"; #computed value 2*3=6; magic_sort(@array); #our to be determined sort function; #after our sort #$array[0] is "23 2 3"; #$array[1] is "25 3 7"; #$array[2] is "68 4 6";
Any help or explanation as to how to do this would be much appreciated.

Replies are listed 'Best First'.
Re: Complex sorting using map
by Kasei (Novice) on Dec 28, 1999 at 07:33 UTC
    @array = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { my @q = split(/\s+/,$_); [ $_, $q[-1] * $q[-2] ] } @array;