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
In reply to Choosing the sort routine on the fly by grinder
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |