in reply to Re: Is it possible to sort using a coderef, without first storing the coderef in a scalar
in thread Is it possible to sort using a coderef, without first storing the coderef in a scalar

The part that I'm not quite sure about is the distinction between these two:
# Doesn't work sort \&numeric @list; # Works my $sorter = \&numeric; sort $sorter @list;
I know that the first example would work if I used numeric instead of \&numeric - but why does \&numeric not also work?

I'm playing with a module that defines a set of common sort patterns, and provides methods that return coderefs that implement the pattern that was requested.

For example, sorting a list of hashes based on the value of a user specified key. The custom implementation would be something like:

sub sort_hashkey($$) { my ($a,$b) = @_; $a->{foo} <=> $b->{foo}; } my @sorted = sort_hashkey @list;
My module provides this:
my $sorter = sorthash_numeric('foo'); my @sorted = sort $sorter @list;
It would be nice, but not neccesary, to do this:
my @sorted = sort sorthash_alpha('foo') @list;
  • Comment on Re^2: Is it possible to sort using a coderef, without first storing the coderef in a scalar
  • Select or Download Code

Replies are listed 'Best First'.
Re^3: Is it possible to sort using a coderef, without first storing the coderef in a scalar
by ikegami (Patriarch) on Jul 26, 2006 at 05:38 UTC

    If you wish to use that syntax, you could use a wrapper.

    sub mysort { my $sorter = shift; return sort $sorter @_; } my @sorted = mysort sorthash_alpha('foo'), @list;
Re^3: Is it possible to sort using a coderef, without first storing the coderef in a scalar
by davido (Cardinal) on Jul 26, 2006 at 05:33 UTC

    Because you have a choice according to the docs for sort. You can use a block, a subname, or (from the docs): "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." There is nothing in the docs that says you can use a subroutine call to return a sub reference. You can use a block, a subname, or a scalar variable containing the name of a sub or a reference to a sub. Nothing else. And your sub named in 'subname' must return an integer (-1, 0 or 1, for example). Likewise, the sub referred to in $subname must return an integer.


    Dave