Perl-Sensitive Sunglasses | |
PerlMonks |
Odd lexical variable behavior -- why does this happen?by radiantmatrix (Parson) |
on Sep 12, 2007 at 20:08 UTC ( [id://638668]=perlquestion: print w/replies, xml ) | Need Help?? |
radiantmatrix has asked for the wisdom of the Perl Monks concerning the following question: I ran across some interesting behavior with lexically-scoped variables; it first struck me as so odd that I thought I'd discovered a bug in my stack1. However, I couldn't believe that I was doing something so unusual that I was the first to discover such a bug, so I built a smaller test case. What results is not, I think, a bug in the stack (oh, yes it is, sort of: see this reply), but is still behavior I don't entirely understand. Perhaps some more enlightened monk can assist me. I know, of course, that when I store a reference to a lexically-scoped value, then let the original go out of scope, the reference still exists, so the variable is not entirely destroyed. However, it surprised me to learn that I can enter that scope again, specifically set the value of the variable, and not have it work. Check it out:
Note how I specifically state my $progress = 0; in the sub. If I click the button 3 times, thus calling the sub 3 times, I get the following console output:
I don't understand why that's happening -- if I'm setting $progress to zero each time, why does it always increment in that way? I've managed to refactor the production code that has this issue in such a way as to avoid this behavior, so this isn't life-or-death by any stretch. However, it is really bugging me, and I'd appreciate some enlightenment. Thanks in advance! ----- 1: i.e. in some module I was using, its dependencies, or perl itself (yes, I know how unlikely the last is). Updates:
<–radiant.matrix–>
Ramblings and references The Code that can be seen is not the true Code I haven't found a problem yet that can't be solved by a well-placed trebuchet
Back to
Seekers of Perl Wisdom
|
|