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

You can always disable prototypes, but I'm not sure if that's what you meant:

&doit( $codeRef );

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

    That works! I think I did something else though?

    Update: I found the example on the disk image DVD from my old machine;

    doit \&{ $codeRef };;

    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.

      Another way:

      sub testit{ print 'hi' } sub doit (&) { $_[0]->() } $codeRef = \&testit; doit { &$codeRef };

      update (after BrowserUk's response below) -

      My suggestion adds next to nothing, since wrt to sub stacks, $ref->() is just syntactic sugar for &$ref or vice versa. The notation doit \&{ $subref } seems to be the right thing to do:

      #!/usr/bin/perl use Carp qw(cluck); sub testit{ cluck 'hi',$/ };; sub doit (&) { print $_[0],$/;$_[0]->() };; $codeRef = \&testit;; doit { &$codeRef }; __END__ CODE(0x955737c) hi at coderef.pl line 3 main::testit called at coderef.pl line 6 main::__ANON__() called at coderef.pl line 4 main::doit('CODE(0x955737c)') called at coderef.pl line 6
      #!/usr/bin/perl use Carp qw(cluck); sub testit{ cluck 'hi',$/ };; sub doit (&) { print $_[0],$/;$_[0]->() };; $codeRef = \&testit;; doit \&{ $codeRef }; __END__ CODE(0x9f4c11c) hi at coderef.pl line 3 main::testit() called at coderef.pl line 4 main::doit('CODE(0x9f4c11c)') called at coderef.pl line 6
        hmm it even works when passing parameters 8)

        DB<11> $codeRef= sub { print @_ } DB<12> sub doit (&) { $_[0]->("para") } DB<13> doit { &$codeRef } para

        But one should check about the costs of the extra call level ... maybe not too big.

        Cheers Rolf

        Yes, but you're effectively making nested subroutine calls that way, which for small subs can mean a 25% to 30% performance hit


        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.