Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Lexicals in if() scope gotcha!

by BrowserUk (Pope)
on Mar 31, 2004 at 00:55 UTC ( #341164=note: print w/replies, xml ) Need Help??

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 (Archbishop) 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?



Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://341164]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2018-06-23 22:27 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.