in reply to How to safely use $_ in a library function?

I think I like the basic approach of hdb here (elaborated by vsespb here) best, but if it's absolutely necessary to use  $_ come Hell or high water, maybe something like:

>perl -wMstrict -le "for (qw(zik zok)) { print qq{for before: '$_'}; foo('wilma'); print qq{for after: '$_' \n}; } ;; sub foo { local $_ = 'fred'; sub { local $_ = 'XXX'; goto &bar; }->(@_); } ;; sub bar { my ($passed) = @_; print qq{gone from foo, passed = '$passed', \$_ = '$_'}; } " for before: 'zik' gone from foo, passed = 'wilma', $_ = 'fred' for after: 'zik' for before: 'zok' gone from foo, passed = 'wilma', $_ = 'fred' for after: 'zok'

Note that local-ization within the calling context of goto (i.e., within the  sub { ... }) is still wiped out.

Note also: Try:

sub foo { for (qw(fred pebbles)) { sub { for (qw(hoo ha)) { goto &bar; } }->(@_); } }

Replies are listed 'Best First'.
Re^2: How to safely use $_ in a library function?
by perl-diddler (Chaplain) on Sep 18, 2013 at 18:28 UTC
    Regarding 1st solution: Since this code is used to implement pseudo-vars that can be initialized and checked at compile time, inserting an layer of callsub *seems* like a high penalty to pay.

    I tried using the "for" as a $_ specifier, but as soon as it was in the goto-target-func, the value was restored to the one in the outer loop.

    The Internals fix looks like the right way to solve this, as it addresses the problem. However, I solved it by making use of a global, as it's less likely to break. With the current maintainers, the perl feature set is unstable (they yanked lexical $_ out of feature status and into experimental status in 5.18, and forced in a new feature that affects everyone in 5.18 without opting in (via "use 5.18" or use feature "xxx"). Releasing incompatible features in the production version of perl demonstrates their level of commitment to stable interfaces. Heaven knows what they would do to the Internal interfaces.

    Didn't know "lvalue" was also experimental until last week -- as when I started using it, I followed its usage example in some CPAN code ... urg...