in reply to Access a global variable from a subroutine when used as "for" iterator

swl has given a great answer that should help you understand the scope of "iterator" (for loop) variables in Perl for loops, but the real issue here is smelly code! Your sub show would be much better to take $i as a parameter so it is clear everywhere show() is used what is being shown:

for $i (1 .. 3) { show($1); } sub show { my ($i) = @_; print "$i\n"; }

That not only fixes the immediate issue, but makes the code clearer and easier to maintain.

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Replies are listed 'Best First'.
Re^2: Access a global variable from a subroutine when used as "for" iterator
by LanX (Saint) on Dec 20, 2023 at 23:09 UTC
    While I don't think the OP really wanted a closure and knows their purpose, I wouldn't call them "smelly" if used appropriately.

    With this short demo we can't really guess the overall intention.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery

      Closures are not generally smelly, but global variables almost always are. My impression is the OP was aiming for a global variable rather than a closure. Very likely if a closure is intended by an OP the fact is mentioned because that has a strong influence on the expected behavior of the code. No mention, no closure.

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

        It was just to simplify the maintenance of a special portion of the code at the expense of supporting functions/methods. The full story is here.

      You are right... my demo was to present what I found. In the real code, the equivalent to show() function receives a parameter, but under certain conditions, I wanted it to default to the iterator.

        We really need to know more for a good advice. For instance, do you plan to export that function?

        For instance:

        Another possibility it's a second closure function to set this closure variable.

        Yet another is using a full qualified $private::package::var

        In short: TIMTOWTDI, but it depends.

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        see Wikisyntax for the Monastery