in reply to Sorting based on any column

Seems to me that the ability to transparently use <=> (numeric) vs. cmp (string), as-appropriate, is a major part of the question . . . ?

Replies are listed 'Best First'.
Re^2: Sorting based on any column
by Laurent_R (Canon) on May 19, 2015 at 21:28 UTC
    Yes, it seems important, if I understand correctly this OP' quote: "my array is having both characters and numercis".

    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):

    @sorted_array= map { $_->[0] } sort { $numeric ? $b->[1] <=> $a->[1] : $b->[1] cm +p $a->[1]} map { [ $_, (split " ", $_)[$col_2sort] } @unsorte +d_array;
    The other way might possibly look simpler (but is probably less clean and more error-prone):
    @sorted_array= map { $_->[0] } sort { $b->[1] <=> $a->[1] || $b->[1] cmp $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:

    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:

    $ perl -e 'print 3 <=> "b"' 1 ~ $ perl -e 'print 3 cmp "b"' -1
    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.

    Update: Corrected two stupid typos in my code, thanks to AnomalousMonk for proofreading.

Re^2: Sorting based on any column
by Anonymous Monk on May 19, 2015 at 20:46 UTC

    What on earth are you talking about? What does cmp have anything to do with the question?