in reply to Multiple Sort on selected column
The second, and better option, would be to wrap your comparison routine in an anonymous block, like:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my @employees = ( { FIRST => 'Bill', LAST => 'Gates', SALARY => 600000, AGE => 45 }, { FIRST => 'George', LAST => 'Tester', SALARY => 55000, AGE => 29 }, { FIRST => 'Sally', LAST => 'Developer', SALARY => 55000, AGE => 29 }, { FIRST => 'Joe', LAST => 'Tester', SALARY => 55000, AGE => 29 }, { FIRST => 'Steve', LAST => 'Ballmer', SALARY => 600000, AGE => 41 } ); sub cmp_by { my $result = 0; for my $term (@_) { $result ||= $a->{$term} cmp $b->{$term}; } return $result; } print Dumper sort {cmp_by(qw(LAST FIRST))} @employees;
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.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Multiple Sort on selected column
by thundergnat (Deacon) on Oct 18, 2012 at 19:31 UTC | |
by kennethk (Abbot) on Oct 19, 2012 at 15:07 UTC | |
Re^2: Multiple Sort on selected column
by huchister (Acolyte) on Oct 18, 2012 at 18:45 UTC |