in reply to Is it possible to sort using a coderef, without first storing the coderef in a scalar
It is legal to use a coderef with sort, but if you use a named sub, that sub is expected to return -1, 0, or 1. If it returns anything non-numeric such as a coderef, you get a fatal.
Your first example calls get_numeric() once, assigning the coderef it returns to $sorter. $sorter, containing a coderef, has its referant code executed by sort. But get_numeric() is only called once, before the sort routine is ever invoked. This is an important distinction; $sorter contains a coderef, that when executed returns -1, 0, or 1.
In your second example, you should actually write it like this:
my @sorted2 = sort get_numeric (3,2,1);
...because that's syntactically correct. sort doesn't want "get_numeric()", it wants subname, which is "get_numeric" (without the parens). But when you compose it as I've demonstrated above, you get a different error altogether. You get "Subroutine didn't return a numeric value..." Why? Because get_numeric() doesn't return a numeric value... instead it returns a coderef pointing to numeric(). That's an additional level of indirection that sort isn't equipped to dive into once it sees that it's been given a subname.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Is it possible to sort using a coderef, without first storing the coderef in a scalar
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 |