in reply to Regexp vars localization in blocks

In a while loop, there is a per-pass scope that extends beyond the body. The loop expression is evaluated in this scope.

In a foreach loop, you also have a per-pass scope that extends beyond the body of the loop. The loop iterator var is found in this scope.

While a C-style for loop has a statement-wide scope, doesn't have a per-pass scope beyond the loop body.

map and bare loops similarly don't have a per-pass scope beyond the loop body.

I don't know much about $& localization, but the results correlate to the existence of that larger per-loop scope.

Replies are listed 'Best First'.
Re^2: Regexp vars localization in blocks
by Anonymous Monk on Jul 28, 2023 at 20:55 UTC

    This C-style for:

    1 =~ /1/; for (my $i = 3; $i =~ /[34]/; $i++) { print $&; } print $&;

    says 341, not 344. Isn't it because of beyond-body, outer-implied-braceless scope, which is same as in similar while loop?

    Or did you mean something else, by "per-pass" (is it same as "per-loop") scope? The confusing part is why $& in OP (but not localized $x in hv's code) preserves its value between iterations.

    And further (maybe unrelated; sorry, have just seen it, can't un-see):

    1 =~ /1/; for ((my $i = 3) =~ /./; $i =~ /[34]/; $i++) { print $&; } print $&;

    says 343. Again, sorry if it's waste of time, these are (questionably) good in idle golf etc., seem not have bothered busy people in 30+ (?) years.