|Keep It Simple, Stupid|
Unusual Closure Behaviourby tachyon (Chancellor)
|on Jul 12, 2001 at 10:55 UTC||Need Help??|
tachyon has asked for the
wisdom of the Perl Monks concerning the following question:
I came across an unusual form of closure that I would like someone to explain to me. You make a regular closere like this:
This prints 1234567 because Perl maintains the $x variable as sub foo's private memory. OK no suprises there. It's a closure.
Why does this code produce the same effect?
It must be a closure but why does Perl maintain the $x var. If you remove the if undef $x behaves as a lexically scoped var, so as expected we print 1111111 as $x is destroyed and recreated every time you call the sub. However with this added it forms a closure so each time we call foo() $x increments and we print 1234567. A bit of experimentation shows any false value 0, '', or undef elicits this behaviour. Could someone please explain this?