Greeting, I am new to PERL, and I dont know how to implement this multiple sort key.
I am trying to sort given array with given selected column.
See below code
#!/usr/bin/perl
use strict;
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 seniority {
$a->{FIRST} cmp $b->{FIRST} or $a->{AGE} <=> $b->{AGE}
}
my $sort = "FIRST, AGE";
my @sorts = split( ',', $sort );
my @ranked;
for( @sorts )
{
@ranked = sort seniority @employees;
}
foreach my $emp (@ranked) {
print "$emp->{SALARY}\t$emp->{AGE}\t$emp->{FIRST}\t$emp->{LAST}\n"
+;
}
Let say I want to sort only the Last, and Salary. then I'd have to change {FIRST} or {AGE} value in this case.
Also, What if I want to add $sort key, ex) "FIRST, AGE, LAST", I'd have to add method to seniority, but dont know how.
This would be great example for multiple sort given key variables. I would try to use basic 'sort' method as possible, not modifying or inserting new Sort::Key, or any other.
UPDATE : This problem was solved using kennethk's method. Please see below for additional info.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|