Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: providing a callback routine to sort

by pemungkah (Priest)
on Jan 21, 2014 at 22:04 UTC ( #1071530=note: print w/replies, xml ) Need Help??


in reply to providing a callback routine to sort

Just did this the other day. The key is to remember that sort's curly block is essentially an anonymous sub, so what you put there has to be executable code. In the case of a sort subroutine, this means you need to do something like this:
my $dir = shift; my $sort_sub = $dir eq 'up' ? sub {$a <=> $b} : sub {$b <=> $a}; my @items = (3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5); print "@{[sort { $sort_sub->() } @items]}\n";
Which gives us
$ perl sample up 1 1 2 3 3 4 5 5 5 6 9 $ perl sample down 9 6 5 5 5 4 3 3 2 1 1
Note that the code in the sort curlies calls the callback itself.

Replies are listed 'Best First'.
Re^2: providing a callback routine to sort
by Anonymous Monk on Jan 21, 2014 at 22:41 UTC
      So it is - thanks! I'm just so used to having the curlies in there that I'd forgotten I could drop them.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1071530]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (3)
As of 2022-05-28 01:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Do you prefer to work remotely?



    Results (98 votes). Check out past polls.

    Notices?