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] @list

But 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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • 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, details, 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, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.