Recently I had to sort some records based on the values of 2 different fields, for example, given

X 4143 61 Y 51 1325 Z 543 1543
I wanted them sorted this way:
Y 51 1325 X 4143 61 Z 543 1543

Because 51 is lower than 61, and the latter lower than 543

Surely this is nothing new, but I found the solution quite instructive, so I decided to share it here

It uses Schwartzian transformation. An explanation could be found here

Comments are welcome

citromatik

use strict; use warnings; use Data::Dumper; my @sorted = map {pop @$_ } sort { $a->[0] <=> $b->[0] || $a->[1] <=> $b->[1] } map { [ (sort { $a <=> $b } @$_[1,2]),$_ ] } map { [split /\s+/] } <DATA>; print Dumper \@sorted; __DATA__ A 15134 135 B 413 6161 C 33 16199 D 16141345 135

Replies are listed 'Best First'.
Re: Sorting on 2 fields with the same priority
by Limbic~Region (Chancellor) on Feb 08, 2008 at 14:56 UTC
    citromatik,
    If I understand your problem correctly, you are sorting collections by the lowest value found in each collection. If this is the case, then you should modify your solution to use List::Util's min() since sorting the list to find an extreme is wasteful.

    Cheers - L~R

Re: Sorting on 2 fields with the same priority
by citromatik (Curate) on Feb 08, 2008 at 15:34 UTC
    If I understand your problem correctly, you are sorting collections by the lowest value found in each collection

    Well, not exactly, I am sorting collections considering 2 values. If the lowest value of 2 collections are the same, I use the higher for untie. In the example I give in the post:

    A 15134 135 D 16141345 135

    After sorting A will be placed before D because although they have the same lower value (135), A has the lower higher.

    You can't do that with List::Util's min, because it only returns the mininum value

    citromatik
      citromatik,
      I would still avoid sort.
      my @sorted = map $_->[0], sort {$a->[1] <=> $b->[1] || $a->[2] <=> $b->[2]} map { my (undef, $val1, $val2) = split " "; ($val1, $val2) = ($val2, $val1) if $val2 < $val1; [$_, $val1, $val2]; } <DATA>; # Untested

      Cheers - L~R