diotalevi has asked for the wisdom of the Perl Monks concerning the following question:
Is there some reliable way that a subroutine can gain access to itself as a code reference? I can do this as a closure but I wondered if there was something generalizable so any subroutine, closure or not, could alter itself.
I'm specifically thinking of subroutines that can terminate themselves and prevent further access. Here's a code snippet where I'm hoping for something more general.
sub purse { my $balance = shift; my $sub; $sub = sub { my ($who, $qty) = @_; print "Paying $who $qty\n" if ($balance - $qty) >= 0; undef $sub if $balance <= 0 }; } { my $payment = purse(10); for ([qw/mom 7/], [qw/dad 3/], [qw/myself 1/]) { $payment->(@$_) if $payment; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: Giving subroutines access to themselves
by merlyn (Sage) on Dec 17, 2002 at 19:23 UTC | |
by diotalevi (Canon) on Dec 17, 2002 at 19:29 UTC | |
|
Re: Giving subroutines access to themselves
by MarkM (Curate) on Dec 17, 2002 at 19:38 UTC | |
by diotalevi (Canon) on Dec 17, 2002 at 19:47 UTC | |
|
Re: Giving subroutines access to themselves
by BrowserUk (Patriarch) on Dec 17, 2002 at 19:55 UTC | |
|
Re: Giving subroutines access to themselves
by jdporter (Paladin) on Dec 17, 2002 at 19:34 UTC | |
|
Re: Giving subroutines access to themselves
by dpuu (Chaplain) on Dec 17, 2002 at 20:18 UTC | |
|
Re: Giving subroutines access to themselves
by djantzen (Priest) on Dec 17, 2002 at 19:35 UTC | |
by diotalevi (Canon) on Dec 17, 2002 at 19:46 UTC |