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

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

Thread Previous | Thread Next
From:
Johan Vromans
Date:
July 11, 2008 09:03
Subject:
Re: my $foo = "bar" if $baz;
Message ID:
m2od54z9us.fsf@phoenix.squirrel.nl
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;

-- Johan

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