in reply to Re: Passing arguments to callback routines with named references
in thread Passing arguments to callback routines with named references

Or shorter:
  sub callback { shift->( @_ ) }
Liz
  • Comment on Re: Re: Passing arguments to callback routines with named references

Replies are listed 'Best First'.
Re: Re: Re: Passing arguments to callback routines with named references
by sauoq (Abbot) on Jul 15, 2003 at 17:28 UTC
    Or shorter:

    No. This is wrong and not just for the obvious reasons. Your "correction",

    sub callback { sub { shift->( @_ ) } }
    is just as wrong.

    The term closure is not synonymous with "code reference." You are returning a reference to a sub that, when called with a coderef and some arguments, immediately calls that coderef with those arguments. And that isn't very useful at all because the reference you return won't be able to be called with arguments anyway!!! So, your shorter "solution" just brings us full-circle to the original problem and fails to add anything but complexity.

    First, have a look at the problem...

    sub callback { my $coderef = shift; my @args = @_; sub { $coderef->(@args) } } sub short_but_wrong { sub { shift->(@_) } } sub foo { print "@_\n" } my $mine = callback( \&foo, 1, 2, 3 ); my $yours = short_but_wrong( \&foo, 1, 2, 3 ); print "Mine: "; $mine->(); print "Yours: "; $yours->();
    That outputs:
    X: 1 2 3 Undefined subroutine &main:: called at cback line 7.
    Why? Because the call, $yours->(), didn't supply an argument so the shift resulted in undef which isn't a valid code reference.

    The whole point of a closure is that it captures its lexical environment. It binds the code with some variables. Your "shortening" eliminates the lexical environment entirely; there is nothing to capture, so it isn't a closure at all.

    Since you need the lexicals, you won't shorten my original (without crunching whitespace and picking shorter identifiers) by much more than this:

    sub callback { my ( $coderef, @args ) = @_; sub { $coderef->( @args ) } }

    -sauoq
    "My two cents aren't worth a dime.";
    
      Indeed. You're absolutely right.

      I can only blame the hot weather.

      Thank you for elaborating.

      Liz

Re: Re: Re: Passing arguments to callback routines with named references
by ctilmes (Vicar) on Jul 15, 2003 at 14:09 UTC
    I don't think that is right.

    You're not building the closure -- you're just calling the coderef.

      You're right, it should have read:
        sub callback { sub { shift->( @_ ) } }
      
      Liz