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; }
In reply to Is it possible to sort using a coderef, without first storing the coderef in a scalar by imp
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |