http://www.perlmonks.org?node_id=341164


in reply to Lexicals in if() scope gotcha!

#! perl -slw use strict; { package Foo; sub new{ bless {}, $_[ 0 ]; } sub DESTROY{ print "destroying $_[0]" } } if( my $x = Foo->new ) { print "Created $x"; } print "After first if"; if( my $x = Foo->new and 0 ) { print "Created $x"; } else{ print "Created $x but failed the if"; } print "After second if/else"; { if( my $x = Foo->new ) { print "Created $x"; } print "After third if"; } print "exited block"; __END__ P:\test>test Created Foo=HASH(0x22501c) After first if Created Foo=HASH(0x225028) but failed the if After second if/else Created Foo=HASH(0x225040) After third if destroying Foo=HASH(0x225040) exited block destroying Foo=HASH(0x225028) destroying Foo=HASH(0x22501c)

When you create a lexical within the condition of an if statement, the scope is notionally the body of the if block, but as shown above in the second example, the scope actually has to extend to any else block also.

To achieve this, the life of the lexical has to extend beyond the life of the if block, and so in the first two examples, whilst it's scope is defined by the if/else construct, it's life is bounded by the package level. In effect, it becomes a closure(*incorrect, but common term), within those blocks, but cannot be destroyed until the surrounding scope (the package main in this case) exits.

In the third example, there is a scope enclosing the if construct and so the variable can be destroyed when that enclosing scope is exited, rather than waiting for package to finish.

I guess setting the refcount to 2 is the mechanism by which closures(*) work?


Examine what is said, not who speaks.
"Efficiency is intelligent laziness." -David Dunham
"Think for yourself!" - Abigail

Replies are listed 'Best First'.
Re: Re: Lexicals in if() scope gotcha!
by davido (Cardinal) on Mar 31, 2004 at 06:57 UTC
    Out of curiosity, is the same true of while loops and foreach loops, where continue blocks might place the same constraints on lexicals as else blocks do for if constructs?


    Dave

      Yes.