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
In reply to Sorting on 2 fields with the same priority by citromatik
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |