<?xml version="1.0" encoding="windows-1252"?>
<node id="95940" title="Unusual Closure Behaviour" created="2001-07-12 06:55:00" updated="2005-08-12 07:58:43">
<type id="115">
perlquestion</type>
<author id="80749">
tachyon</author>
<data>
<field name="doctext">
&lt;p&gt;I came across an unusual form of closure that I would like someone to explain to me. 
You make a regular closere like this:
&lt;code&gt;
{
    my $x;
    sub foo {
        return ++$x;
    }
}

for (1..7) { print foo() }
&lt;/code&gt;
&lt;p&gt;This prints 1234567 because Perl maintains the $x variable as 
sub foo's private memory. OK no suprises there. It's a closure.
&lt;p&gt;Why does this code produce the same effect? 
&lt;code&gt;
sub foo {
    my $x if undef;
  return ++$x;
}
for (1..7) { print foo() }
&lt;/code&gt;
&lt;p&gt;It must be a closure but why does Perl 
maintain the $x var. If you remove the  &lt;tt&gt;if undef&lt;/tt&gt;  $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?
&lt;p&gt;cheers
&lt;p&gt;&lt;font color="#0000ff"&gt;tachyon&lt;/font&gt;
&lt;p&gt;s&amp;amp;&amp;amp;rsenoyhcatreve&amp;amp;&amp;amp;&amp;amp;s&amp;amp;n.+t&amp;amp;"$'$`$\"$\&amp;amp;"&amp;amp;ee&amp;amp;&amp;amp;y&amp;amp;srve&amp;amp;&amp;amp;d&amp;amp;&amp;amp;print
</field>
</data>
</node>
