I was playing with sorting using a code reference, and found that I cannot obtain the code reference through a subroutine call without first storing the reference in a scalar.

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:

my $sorter = \&some_function; sort $sorter (1,2,3);
Bad:
sort \&some_function (1,2,3);
It is also an error to obtain the coderef from a factory, without first storing the coderef in a scalar.
sort make_sorter() (1,2,3)
(Where make_sorter is a function that returns a coderef. The referenced sub being a valid sort function.)
End edit

Original example:

This code works as expected:

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; }
This code does not work at all:
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; }
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?

Environment is perl 5.8.2 on openbsd.

In reply to 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.