in reply to Re^4: How do closures and variable scope (my,our,local) interact in perl?
in thread How do closures and variable scope (my,our,local) interact in perl?

[ The parent post initially ended at "Do I have that right?". This addresses the second half ]

As for the troubling difference, I suppose I think of file scope my variables as the "same kind" of variable as "our" variables, just private to a file.

There's nothing special about the file scope. It's just like every other scope. All the differences between lex and pkg vars (access, ability to capture, lifespan, etc) exist whether they are in a block or nested deeper.

All the same, outside of the for loop I expect anything associated with file scope $x to have the value assigned to file scope $x. But that is not what happens.

I explained what happens here.

In short, when you capture, you link to the SV associated with the captured name. Since foreach loops change which SV is associated with the iterator each pass of the loop ("aliasing"), you capture something different every pass of the loop.

when captured by a closure, the our variable loses its aliased association outside of the for loop, the file scope my variable does not.

The last bit is wrong. It does indeed lose its aliasing (and localisation).

my $y = 5; my $x; for $x ($y) { ++$x; print "$y\n"; # 6 } ++$x; print "$y\n"; # 6

For package variables, the name is captured. The SV is looked up in the symbol table. If a different SV is later associated with the captured variable, that SV will be used.

For lexical variables, the SV is captured. If a different SV is later associated with the captured variable, the will not be closure won't know about it.

  • Comment on Re^5: How do closures and variable scope (my,our,local) interact in perl?
  • Download Code