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


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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.