in reply to Why is it uninitialized?

We had several similar discussions in my years here, but unfortunately I'm not able to find them now.(wait°)

Point is IIRC - like others already said - that "localizing" the lexical happens by binding a new place to the symbol S4.

Localizing isn't done like in local (safe/restore) with package vars on the same place.

I'm not sure, but I seem to remember that the implementation of foreach involves an extra "frame" with an own lexpad.

The whole mess is probably a side effect of the late introduction of lexicals after Perl 4.

Best solution for your problem is to use another symbol for the loop and to copy the value to the closure var.

for my $x (1 .. 2) { my $S4 =$x; print "A: <$S4> <", X(), ">\n"; }

> It's breaking my mental model of Perl, 

That's because Perl is kind of broken here ...

... or to phrase it better, foreach with its aliasing is a very magic beast inside Perl.

update

°) for instance How do closures and variable scope (my,our,local) interact in perl?

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