Several times I came across the following pattern when developing Perl modules that use AUTOLOAD methods or other routine methods:
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 locally set $_ to $self at runtime &$code . Which would be something like this:
sub AUTOLOAD { my $self = $_[0]; my $code = $self->figure_out_code_ref( $AUTOLOAD ); local *_ = \$self;
caller packaging solutions are unacceptable due to performance and dependency issues. So this excludes the second option.
Returning to the first, the only way to prevent a new $_ value from going out of scope during goto is either to not localize the change (not a viable option), or to implement some kind of uplevel_local or goto_with_local .
I played with all kinds of permutations involving PadWalker , Sub::Uplevel , Scope::Upper , B::Hooks::EndOfScope and others, but could not find a reliable solution that clears $_ at the right time and does not complete the caller .
Has anyone found a template that works in this case?
(SO question: How can I localize Perl variables in another stack frame? is connected, but saving caller not a requirement, and ultimately the answer should have used a different approach, so the solution does not help in this case)
perl goto local
Eric Strom
source share