in reply to Lexical scope variable is not undef'ed

(Update: I am misled -- ignore the following)

Your problem is this statement:

my $var = '' if 0;
Which is being parsed as:
if (0) { my $var = ''; }
...And in turn, the statement is skipped entirely. Therefore you are never creating a lexical variable $var -- you are implicitly using a local variable $var, which retains its value from iteration to iteration and then resets itself once the loop is exited.

perlsyn explains it.

Example:

bash$ perl -e 'for(1..3){my $i if 0; print $i++, "\n"}' 0 1 2 bash$ perl -e 'for(1..3){my $i if 1; print $i++, "\n"}' 0 0 0

Replies are listed 'Best First'.
Re^2: Lexical scope variable is not undef'ed
by ikegami (Patriarch) on Oct 22, 2007 at 16:53 UTC

    That's not true. It's not parsed as if (0) { my $var = ''; }, and it does create a lexical $i (my's compile-time effect).

    >perl -le "$::i=q{Pass }; for(1..3){my $i if 0; ++$i; print $::i, $i}" Pass 1 Pass 2 Pass 3 >perl -le "$::i=q{Pass }; for(1..3){ ++$i; print $::i, $i}" 11 22 33

    What happens is that the clearing doesn't occur at the end of the scope (my's run-time effect). See Re: Lexical scope variable is not undef'ed.