Or shorter:
No. This is wrong and not just for the obvious reasons. Your "correction",
is just as wrong.sub callback { sub { shift->( @_ ) } }
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...
That outputs: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->();
Why? Because the call, $yours->(), didn't supply an argument so the shift resulted in undef which isn't a valid code reference.X: 1 2 3 Undefined subroutine &main:: called at cback line 7.
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.";
In reply to Re: Re: Re: Passing arguments to callback routines with named references
by sauoq
in thread Passing arguments to callback routines with named references
by nysus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |