"be consistent" | |
PerlMonks |
Re: Multiple Sort on selected columnby kennethk (Abbot) |
on Oct 18, 2012 at 18:24 UTC ( [id://999791]=note: print w/replies, xml ) | Need Help?? |
So, in order to implement your desired flexible sort, you need to pass information into your comparison routine. However, you cannot specify arguments to a sub passed to sort directly. There are two straight-forward solutions to this, in my mind. The first would be to use a closure about an array, which I expect would be less maintainable and look more magical under maintenance.
The second, and better option, would be to wrap your comparison routine in an anonymous block, like:
The way I've written it, you pass an array of keys (see qw in Quote and Quote like Operators in perlop) to your comparison function. The comparison function cycles over that list each time sort calls the block wrapped around it, storing the first time the comparison doesn't yield 0 and returning the result. Side notes: The language is Perl and the interpreter is perl; there is no PERL. Also, note I've added warnings to my demo code, which can be a real life saver: see Use strict warnings and diagnostics or die. Update: Note, as thundergnat was kind enough to point out below (and Tanktalus via msg), SALARY and AGE are numeric fields, and should be sorted using the numeric comparison operator, <=>. The code above will sort improperly on numbers that are not the same length (so would appear to succeed on AGE). Of course, as I've noted below, his is not without difficulty... #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
In Section
Seekers of Perl Wisdom
|
|