http://qs321.pair.com?node_id=95940

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:

{ my $x; sub foo { return ++$x; } } for (1..7) { print foo() }

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?

sub foo { my $x if undef; return ++$x; } for (1..7) { print foo() }

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?

cheers

tachyon

s&&rsenoyhcatreve&&&s&n.+t&"$'$`$\"$\&"&ee&&y&srve&&d&&print