Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^2: Sorting based on any column

by Laurent_R (Canon)
on May 19, 2015 at 21:28 UTC ( [id://1127189]=note: print w/replies, xml ) Need Help??


in reply to Re: Sorting based on any column
in thread Sorting based on any column

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1127189]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (4)
As of 2024-04-24 20:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found