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"; }

In reply to Re: Access a global variable from a subroutine when used as "for" iterator by swl
in thread Access a global variable from a subroutine when used as "for" iterator by vitoco

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.