in reply to Choosing the sort routine on the fly

How about this?
#! /usr/local/bin/perl -w use strict; sub forward {$a cmp $b} # removed prototype sub backward {$b cmp $a} # removed prototype my @sorter = qw/forward backward/; my @list = qw(kholsky stencil dnubietna barkhausen manganese fairing fleische flake schlozhauer gascoigne); my $offset = shift || 0; my $subname= $sorter[$offset]; print "$_\n" for sort $subname @list;
Simply supply the sort routine's name.

Update: Thanks to kwaping for noticing that this doesn't work. In fact I oversaw the word "forward" inside the output. To fix it I needed the 3 changes shown above. Prototype must be removed because If the subroutine's prototype is "($$)", the elements to be compared are passed by reference in @_, as for a normal subroutine.. The aditional $subname is needed because: SUBNAME may be a scalar variable name (unsubscripted), in which case the value provides the name of (or a reference to) the actual subroutine to use.

s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
+.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

Replies are listed 'Best First'.
Re^2: Choosing the sort routine on the fly
by kwaping (Priest) on Sep 08, 2006 at 15:42 UTC
    I don't think this works. Here's the output I got from your code:
    barkhausen dnubietna fairing flake fleische forward gascoigne kholsky manganese schlozhauer stencil
    As you can see, the word "forward" was simply added to the list to be sorted. If I supply an $offset of 1, the word "backward" is added to the list of sorted words instead.

    ---
    It's all fine and dandy until someone has to look at the code.