I have run across the following pattern a few times while developing Perl modules that use AUTOLOAD or other subroutine dispatch techniques:
sub AUTOLOAD {
my $self = $_[0];
my $code = $self->figure_out_code_ref( $AUTOLOAD );
goto &$code;
}
This works fine, and caller sees the correct scope.
Now what I would like to do is to locally set $_ equal to $self during the execution of &$code. Which would be something like this:
sub AUTOLOAD {
my $self = $_[0];
my $code = $self->figure_out_code_ref( $AUTOLOAD );
local *_ = \$self;
# and now the question is how to call &$code
# goto &$code; # wont work since local scope changes will
# be unrolled before the goto
# &$code; # will preserve the local, but caller will report an
# additional stack frame
}
Solutions that involve wrapping caller are not acceptable due to performance and dependency issues. So that seems to rule out the second option.
Moving back to the first, the only way to prevent the new value of $_ from going out of scope during the goto would be to either not localize the change (not a viable option) or to implement some sort of uplevel_local or goto_with_local.
I have played around with all sorts of permutations involving PadWalker, Sub::Uplevel, Scope::Upper, B::Hooks::EndOfScope and others, but have not been able to come up with a robust solution that cleans up $_ at the right time, and does not wrap caller.
Has anyone found a pattern that works in this case?
(the SO question: http://stackoverflow.com/questions/200578/how-can-i-localize-perl-variables-in-a-different-stack-frame is related, but preserving caller was not a requirement, and ultimately the answer there was to use a different approach, so that solution is not helpful in this case)