in reply to The & prototype and code references in scalars.

sub testit{ print 'hi' };; sub doit (\&) { $_[0]->() };; my $codeRef = \&testit;; doit( &$codeRef );
or:
sub doit2 (&) { $_[0]->() }; doit2( sub { print 'hi2' });
I've a thing about prototypes, don't ya just love em!

Replies are listed 'Best First'.
Re^2: The & prototype and code references in scalars.
by BrowserUk (Patriarch) on Feb 17, 2010 at 20:47 UTC

    The first example isn't an option because the sub in question is in a module (threads::async()). Also it defeats the most common use case of an in-line bareblock.

    The latter doesn't help as I only have (multiple) coderefs at the place of use. I could use async{ $coderef->( ... ) };, but I'm not keen on the doubling of the call overhead.

    I just rediscovered async \&{ $codeRef };. I'm not sure if that's equally costly.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      We had this discussion recently¹, unfortunately you can't define a prototype which allows literal codeblocks and coderefs (resp. scalars) at the same time.

      You can allow alternatives with (\[&$]) but alas there is no ([&$]) 8(

      At least you can spare the curlies async \&$codeRef ; !

      Cheers Rolf

      ¹) update see coderefs and (&) prototypes

        Thanks for the reference. I think I must have been away that day cos I do not remember that thread at all. And looking at my posting history, I didn't post anything that entire week.

        With regard to \&{ $coderef } versus \&$coderef: I discovered long ago that

        • there is no performance difference between sigil{ $scalar } & sigil$scalar;
        • and that (for example) print for @{ $_[0] } works, where print for @$_[0] doesn't.

        Hence, the 2-char longer (4 if you count my preferred whitespacing) form has no downsides and benefits from the extra clarity when the scalar being dereferenced comes from a compound source. Plus I do not have to try and remember when I have to use the longer form and when I can get away with the shorter. And I like consistency.


        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.