in reply to subref with stored argument?

Although the other answers are fine, there is a subtlety you might want to be aware of. Calling the function from the anonymous sub will affect the call stack. You can avoid that by using the magical goto &sub form.

sub foo { print "foo @_\n"; for (0..2) { print join('|', caller($_)), "\n" if caller($_); } print "\n"; } my $r1 = sub { foo("bar", @_) }; my $r2 = sub { unshift @_, "bar"; goto &foo }; foo(); $r1->('baz'); # This call has an extra frame in the call stack. $r2->('baz', 'qux');

One word of caution. Using this technique will make your prototypes pretty useless. That's OK though because usually prototypes are worse than useless anyway. You almost certainly shouldn't be using them. If you do choose to use them, you should first have a good understanding of the points raised in this article by Tom Christiansen.

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re: Re: subref with stored argument?
by BrowserUk (Patriarch) on Jan 10, 2003 at 03:58 UTC

    The only problem with using the magical goto is that for some reason it is incredibly slow.

    If performance isn't an issue, then it's fine, but if performance is an issue avoid it like the plague:)

    #! perl -slw use strict; use Benchmark qw[cmpthese]; sub recipe{ my @rice = @_; my $grains = scalar @rice; return $grains; +} sub curry { recipe( 'extra', @_) } sub spagetti { unshift @_, 'extra'; goto &recipe; } print recipe qw[1 2 3 4 5 6 7 8 9 0]; print curry qw[1 2 3 4 5 6 7 8 9 0]; print spagetti qw[1 2 3 4 5 6 7 8 9 0]; cmpthese( -10, { recipe => 'recipe qw[1 2 3 4 5 6 7 8 9 0];', curry => 'curry qw[1 2 3 4 5 6 7 8 9 0];', spagetti=> 'spagetti qw[1 2 3 4 5 6 7 8 9 0];', }); __END__ c:\test>225691 10 11 11 Benchmark: running curry, recipe, spagetti , each for at least 10 CPU seconds ... curry: 11 wallclock secs (10.41 usr + 0.00 sys = 10.41 CPU) @ 11 +838.29/s (n=123284) recipe: 10 wallclock secs (10.29 usr + 0.00 sys = 10.29 CPU) @ 15 +358.48/s (n=157962) spagetti: 9 wallclock secs (10.31 usr + 0.00 sys = 10.31 CPU) @ 75 +02.96/s (n=77393) Rate spagetti curry recipe spagetti 7503/s -- -37% -51% curry 11838/s 58% -- -23% recipe 15358/s 105% 30% -- c:\test>

    Examine what is said, not who speaks.

    The 7th Rule of perl club is -- pearl clubs are easily damaged. Use a diamond club instead.