in reply to Re: Re: static-like persistence of my variable due to trailing conditional
in thread static-like persistence of my variable due to trailing conditional

It looks like you are absolutely right. The output of perl -MO=Deparse,-p a.pl follows (after removing Data::Dumper):

sub mycode { (my $var = $_[0]); (defined($var) ? print("mycode() called with $var\n") : print("mycode() called with no operands.\n")); ($var and (my $foo = 'blah')); #^^^^^^^^^^^^^^^ Look here ($foo and print("foo is $foo\n")); ($foo ||= 'FOO'); } mycode('test'); mycode(); mycode(); mycode(); a.pl syntax OK

my $foo = 'blah' is optimized away.

In order to make it behave as expected, my $foo; needs to be its own statement, with no conditional.

Update: Removed bit about strict, see the follow up

Replies are listed 'Best First'.
Re: Re: Re: Re: static-like persistence of my variable due to trailing conditional
by meonkeys (Chaplain) on Jun 29, 2002 at 22:52 UTC
    my $foo = 'blah' is optimized away. It looks like $foo is still in the symbol table for mycode, so strict doesn't complain on any subsequent calls.
    Hmm. I don't agree and/or don't completely understand what you're saying. (1) What do you mean by "optimized away"? (2) if $foo is in a symbol table, can you provide example code to print foo outside of the sub mycode{} block?

    On a side note, does anyone know of links/books/perldoc that I can look at which document this "feature"?

    ---
    "A Jedi uses the Force for knowledge and defense, never for attack."
      1. ($var and (my $foo = 'blah'));The second part of this statement will never be executed if $var is undefined. The 'and' is short-circuited, so the second part of the statement (the re-initialization of $foo) is optimized away never evaluated.
      2. You are right. Poor use of the term "symbol table" on my part, since $foo is a lexical variable. I just got typing too fast ;-) However, I never meant to say that $foo was available outside of the block. What I meant was that it was initialized on the first call to mysub and retains the original value within that block since it is never re-initialized, just like using a sub to create a static variable as in perlfaq7. You can also get the same result (a static variable) by using my $i = 0 if 0;
      On a side note, does anyone know of links/books/perldoc that I can look at which document this "feature"?
      I think this feature should be spelled 'b-u-g'

      And about strict not complaining, I was just plain wrong.

      Update: Changed "optimized away" - Aristotle++.

        You're using wrong terminology here. The my part is not optimized away; that would imply that it gets removed from the optree entirely after the compiler has parsed the source, which is not the case.

        The term you are looking for is "shortcircuit evaluation", which means that once an expression's "truth" can no longer change, the rest of it is not even evaluated.

        Makeshifts last the longest.