[Lexical $_
was removed in v5.24]
Perl v5.10 introduced given
and the lexical $_
. That use of $_
, which everyone has assumed is a global variable, turned out to be a huge mistake. The various bookkeeping on the global version didn’t happen with the lexical version, so strange things happened.
You saw the problem in Use for instead of given. For that reason, we recommended substituting for
instead of given
since when
acts the same in either (which was a correction to Use given-when to make a switch statement from the book).
Previously I showed this program, which up to v5.16 showed that the $_
remembered the value of pos
from previous runs even with a new variable (each call to try_given
has a new $s
):
use v5.10; my $s = "abc"; try_given($s) for 1 .. 3; sub try_given { my $s = shift; state $n = 0; given ($s) { /./g; # $_ here is now the lexical version printf "%d. given: pos=%d\n", ++$n, pos; } }
Under v5.10 to v5.14, the value of pos
advances by one each time although it should work on a new variable:
% perl5.10 try_given.pl 1. given: pos=1 2. given: pos=2 3. given: pos=3
Under v5.16, the magic on $_
works and pos
reports the correct value:
% perl5.16 try_given.pl 1. given: pos=1 2. given: pos=1 3. given: pos=1