Perl-Sensitive Sunglasses | |
PerlMonks |
Re^2: Sorting based on any columnby Laurent_R (Canon) |
on May 19, 2015 at 21:28 UTC ( [id://1127189]=note: print w/replies, xml ) | Need Help?? |
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): The other way might possibly look simpler (but is probably less clean and more error-prone): 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: 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.
In Section
Seekers of Perl Wisdom
|
|