jkeenan1 has asked for the wisdom of the Perl Monks concerning the following question:
According to the Camel book (3rd ed, p 789-90), when using a subroutine to provide the formula for a sort operation,
"USERSUB may be a scalar variable name ..., in which case the value provides either a symbolic or a hard reference to the actual subroutine to use." Thus, the following DWIMs:sort USERSUB LIST
my $mysortref = sub { lc($data{$a}[0]) cmp lc($data{$b}[0]) || lc($data{$a}[1]) cmp lc($data{$b}[1]) }; @results = sort $mysortref (keys %data);
For a complete example -- sorting by last name and breaking ties by first name (both in ascending order) -- see here:
my (%data, @results); while (<DATA>) { my @temp = split; $data{$temp[2]} = [@temp]; } my $mysortref = sub { lc($data{$a}[0]) cmp lc($data{$b}[0]) || lc($data{$a}[1]) cmp lc($data{$b}[1]) }; @results = sort $mysortref (keys %data); print "@{$data{$_}}\n" for (@results); __DATA__ HERNANDEZ HECTOR 456791 SAMSON 0217 2001-07-25 1963-08-0 +1 VASQUEZ JOAQUIN 456789 SAMSON 0209 1990-11-14 1970-03-2 +5 JONES TIMOTHY 803092 LAVER 0103 2001-03-19 1969-06-2 +9 SMITH BETTY_SUE 698389 SAMSON 0211 1992-01-23 1949-08-1 +2 VASQUEZ LEONARDO 456788 LAVER 0107 1990-08-23 1970-15-2 +3 SMITH HAROLD 359962 TRE 0111 2001-07-19 1973-10-0 +2 VASQUEZ ADALBERTO 786792 LAVER 0104 2001-07-26 1973-08-1 +7 VASQUEZ JORGE 456787 LAVER 0105 1986-01-17 1956-01-1 +3 VAZQUEZ TOMASINA 456790 LAVER 0110 1980-11-14 1960-14-0 +2 WILSON SYLVESTER 498703 LAVER 0110 1983-04-02 1953-06-2 +2 VASQUEZ ALBERTO 906786 TRE 0111 2001-07-15 1953-02-2 +8
But suppose that instead of hard-coding the sort formula I want to be able to build it up on the fly based on a per-call basis. How would I go about that?
For instance, suppose that for some reason I wanted to sort by last name in ascending order but break ties by sorting by first name in ascending order. And suppose further that I wanted to do so by having the anonymous subroutine altered due to configuration information, not due to changes in coding.
Can anyone steer me in the correct direction? I've checked the Camel book and the Perl Cookbook, but not discovered an answer.
Thank you very much.
Jim Keenan
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Building a sorting subroutine on the fly
by brian_d_foy (Abbot) on Nov 29, 2005 at 01:21 UTC | |
by jkeenan1 (Deacon) on Nov 29, 2005 at 03:29 UTC | |
by Tanktalus (Canon) on Nov 29, 2005 at 04:17 UTC | |
by jkeenan1 (Deacon) on Nov 29, 2005 at 10:21 UTC | |
by Tanktalus (Canon) on Nov 29, 2005 at 17:30 UTC | |
| |
by brian_d_foy (Abbot) on Nov 29, 2005 at 05:07 UTC | |
|
Re: Building a sorting subroutine on the fly
by steveAZ98 (Monk) on Nov 29, 2005 at 01:50 UTC | |
|
Re: Building a sorting subroutine on the fly
by salva (Canon) on Nov 30, 2005 at 09:22 UTC |