develooper Front page | perl.perl5.porters | Postings from July 2008

Re: my $foo = "bar" if $baz;

Thread Previous | Thread Next
From:
Abigail
Date:
July 11, 2008 11:31
Subject:
Re: my $foo = "bar" if $baz;
Message ID:
20080711162120.GA32133@almanda
On Fri, Jul 11, 2008 at 06:03:39PM +0200, Johan Vromans wrote:
> Dmitry Karasik <dmitry@karasik.eu.org> writes:
> 
> > I always wandered, if that statement turned out to produce bad
> > side effect, wouldn't it be more sane to convert it to a useful one,
> > f.x. translate 'my $foo = "bar" if $baz' to 'my $foo; $foo = "bar" if $baz"?
> > That would be both expected and useful.
> 
> No, it's different.
> 
>   my $foo = $bar if $baz;
> 
> will *not* change the value of $foo if the condition is false,
> creating a lexical variable that maintains its value. Something that
> is now neatly implemented in 5.10 with the 'state' keyword.
> 
> Try:
> 
>     sub foo {
>         my $foo = 1 if 0;
>         print "foo = $foo\n";
>         $foo++;
>     }
> 
>     foo; foo; foo;


Well, sort of. It doesn't always work that way:

    my $count = 0;
    sub foo {
        my $foo = 1 if 0;
        print "foo = $foo\n";
        $foo ++;
        foo () if $count ++ < 3;
    }
    foo;

In the code above, $foo is undefined each time print() is encountered.


Perl will reuse the structure of the variable if there's no reference to
it left, and won't initialize it because of the 'if 0'. But if there's
a reference left, a new structure will be created and the trick won't work.



Abigail

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About