huchister has asked for the wisdom of the Perl Monks concerning the following question:
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
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.#!/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" +; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Multiple Sort on selected column
by Tanktalus (Canon) on Oct 18, 2012 at 19:34 UTC | |
by huchister (Acolyte) on Oct 19, 2012 at 14:05 UTC | |
Re: Multiple Sort on selected column
by kennethk (Abbot) on Oct 18, 2012 at 18:24 UTC | |
by thundergnat (Deacon) on Oct 18, 2012 at 19:31 UTC | |
by kennethk (Abbot) on Oct 19, 2012 at 15:07 UTC | |
by huchister (Acolyte) on Oct 18, 2012 at 18:45 UTC | |
Re: Multiple Sort on selected column
by DrHyde (Prior) on Oct 19, 2012 at 10:38 UTC | |
Re: Multiple Sort on selected column
by sundialsvc4 (Abbot) on Oct 18, 2012 at 19:57 UTC |
Back to
Seekers of Perl Wisdom