in reply to Re: Two Questions on "my"
in thread Two Questions on "my"

> This is because $i falls out of scope and gets garbage collected each time the loop iterates.

perl is actually a bit smarter than that. The $i that is used on each iteration is the same $i; the value is simply reinitialized on each iteration.

You can prove this to yourself by seeing what memory address the scalar has:

for (1..100) { my $i = 1; print \$i, "\n"; }

However, this only works as long as the variable would be garbage-collected at the end of scope. If the reference count is higher than 1 at end of scope $i is a whole new scalar on each iteration. Observe:

for (1..10) { my $i = 1; push(@is, \$i); print "in loop: ", \$i, "\n"; } print "outside loop: $_\n" for @is;