I can see two ways to go about it. Presumably, when using this function, the user knows what there will be in the column, so that the type of comparison could a parameter passed to the function. Assuming this is Boolean parameter stored in the $numeric variable, it could lead to something like this (untested):
The other way might possibly look simpler (but is probably less clean and more error-prone):@sorted_array= map { $_->[0] } sort { $numeric ? $b->[1] <=> $a->[1] : $b->[1] cm +p $a->[1]} map { [ $_, (split " ", $_)[$col_2sort] } @unsorte +d_array;
This is based on the idea that comparing two strings with <=> will yield 0, a false result, so that, if we have strings, the cmp comparison will be executed and return the correct comparison. But there are at least two downsides with this approach:@sorted_array= map { $_->[0] } sort { $b->[1] <=> $a->[1] || $b->[1] cmp $a->[1] +} map { [ $_, (split " ", $_)[$col_2sort] } @unsorte +d_array;
1. You need to silence out the Argument "foo" isn't numeric in numeric comparison (<=>) at ... warning with the appropriate pragma, and I usually hesitate quite a bit before deciding to silence out any warning (except perhaps, but only very very rarely, the initialized and the deep recursion warnings when I really know for sure it is OK);
2. There are several edge cases where it might break, especially if you have one numeric argument and one non-numeric argument:
So this could work out for a one-off sort if you know your data very well, but this is really not very robust production code.$ perl -e 'print 3 <=> "b"' 1 ~ $ perl -e 'print 3 cmp "b"' -1
Update: Corrected two stupid typos in my code, thanks to AnomalousMonk for proofreading.
In reply to Re^2: Sorting based on any column
by Laurent_R
in thread Sorting based on any column
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |