imp has asked for the wisdom of the Perl Monks concerning the following question:
EDIT 20060726 12:14 - Adding a summary at the top as I did not express my question clearly
It is permissible to sort using a scalar which holds a reference to a function, but it is an error to skip the step that stores the reference in a scalar. I wanted to know the distinction between the two.
Good:
Bad:my $sorter = \&some_function; sort $sorter (1,2,3);
It is also an error to obtain the coderef from a factory, without first storing the coderef in a scalar.sort \&some_function (1,2,3);
(Where make_sorter is a function that returns a coderef. The referenced sub being a valid sort function.)sort make_sorter() (1,2,3)
Original example:
This code works as expected:
This code does not work at all:use strict; use warnings; my $sorter = get_numeric(); my @sorted2 = sort $sorter (3,2,1); print join(', ', @sorted2); sub get_numeric { return \&numeric; } sub numeric($$) { my ($a,$b) = @_; $a <=> $b; }
The error is: syntax error at pmsort line 4, near ") (" Is there a clean way to do this, or is the temporary storage in a scalar required?use strict; use warnings; my @sorted2 = sort get_numeric() (3,2,1); print join(', ', @sorted2); sub get_numeric { return \&numeric; } sub numeric($$) { my ($a,$b) = @_; $a <=> $b; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Is it possible to sort using a coderef, without first storing the coderef in a scalar
by davido (Cardinal) on Jul 26, 2006 at 04:48 UTC | |
by imp (Priest) on Jul 26, 2006 at 05:19 UTC | |
by ikegami (Patriarch) on Jul 26, 2006 at 05:38 UTC | |
by davido (Cardinal) on Jul 26, 2006 at 05:33 UTC | |
|
Re: 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:14 UTC | |
|
Re: Is it possible to sort using a coderef, without first storing the coderef in a scalar
by imp (Priest) on Jul 26, 2006 at 16:50 UTC |