Recently I had to sort some records based on the values of 2 different fields, for example, given
I wanted them sorted this way:X 4143 61 Y 51 1325 Z 543 1543
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 | |
|
Re: Sorting on 2 fields with the same priority
by citromatik (Curate) on Feb 08, 2008 at 15:34 UTC | |
by Limbic~Region (Chancellor) on Feb 08, 2008 at 20:26 UTC |