grinder has asked for the wisdom of the Perl Monks concerning the following question:
I want to be able to sort a list in a number of predefined ways. So I wrote something like this:
#! /usr/local/bin/perl -w use strict; sub forward ($$) {$a cmp $b} sub backward ($$) {$b cmp $a} my $sorter = [\&forward, \&backward]; my @list = qw(kholsky stencil dnubietna barkhausen manganese fairing fleische flake schlozhauer gascoigne); my $offset = shift || 0; print "$_\n" for sort {$sorter->[$offset]->()} @list;
I stumbled a bit on the last line. At first I wanted to pass the coderef directly, with:
sort $sorter->[$offset] @listBut the tokeniser has trouble parsing that. Is there another way to achieve my goal without going through the double layer of code? I'm not really fussed about the performance of the above, but it's always nice to be sure that you're not missing out on something.
update: bonus points to skeeve, that's what I was missing :) Actually, there are a couple more points to take care of: the subs don't get $a and $b automatically (update-update: because of the prototypes, thanks kwaping), and the sorter SUBNAME must be a scalar, not an array reference. Which gives:
#! /usr/local/bin/perl -w use strict; sub forward ($$) {my ($x, $y) = @_; $x cmp $y} sub backward ($$) {my ($x, $y) = @_; $y cmp $x} sub bylen ($$) {my ($x, $y) = @_; length($x) <=> length($y) || $x cmp $y } my @sorter = qw(forward backward bylen); my @list = qw(kholsky stencil dnubietna barkhausen manganese fairing fleische flake schlozhauer gascoigne); my $s = $sorter[shift || 0]; print "$_\n" for sort $s @list;
• another intruder with the mooring in the heart of the Perl
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Choosing the sort routine on the fly
by Skeeve (Parson) on Sep 08, 2006 at 08:12 UTC | |
by kwaping (Priest) on Sep 08, 2006 at 15:42 UTC | |
|
Re: Choosing the sort routine on the fly
by hawtin (Prior) on Sep 08, 2006 at 08:05 UTC | |
|
Re: Choosing the sort routine on the fly
by BrowserUk (Patriarch) on Sep 08, 2006 at 08:09 UTC | |
by grinder (Bishop) on Sep 08, 2006 at 10:54 UTC | |
|
Re: Choosing the sort routine on the fly
by sgifford (Prior) on Sep 08, 2006 at 16:23 UTC | |
by Skeeve (Parson) on Sep 08, 2006 at 23:26 UTC | |
|
Re: Choosing the sort routine on the fly
by Limbic~Region (Chancellor) on Sep 08, 2006 at 12:44 UTC | |
|
Re: Choosing the sort routine on the fly
by Outaspace (Scribe) on Sep 08, 2006 at 23:35 UTC | |
by tilly (Archbishop) on Sep 09, 2006 at 00:59 UTC |