in reply to Access a global variable from a subroutine when used as "for" iterator
The first para of this section of perlsyn is relevant here: https://perldoc.perl.org/perlsyn#Foreach-Loops, specifically:
If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only for non C-style loops.
So the variable is localised inside the loop, but your sub wrapped over the original, non-localised version which is not updated.
It's a bit like generating a new my $i inside a new sub, e.g. inner_sub the code below.
There is perhaps an issue of clarity in the docs given one cannot call local on a lexical variable but that text might pre-date the introduction of my declarations (and localization might not be referring to the local keyword).
#!perl use strict; use warnings; our $i = 0; for (1 .. 3) { show(); } inner_sub(); sub inner_sub { my $i = 8; show(); }; sub show { print "$i\n"; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Access a global variable from a subroutine when used as "for" iterator
by Dallaylaen (Chaplain) on Jan 02, 2024 at 09:30 UTC |