justjohn has asked for the wisdom of the Perl Monks concerning the following question:

First the code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; foreach my $i(1..2) { my $j = 47 if 1 == 2; print "loop1 $i - ", Dumper($j); $j = 99; print "after $i - ", Dumper($j); } foreach my $i(1..2) { my $j; $j = 47 if 1 == 2; print "loop2 $i - ", Dumper($j); $j = 99; print "after $i - ", Dumper($j); }

I would expect these two loops to behave identically, and in doing so act as the second one does. The first one is declaring the variable but not initializing it to undef before failing to assign the value to it. And that is making it retain the value from the prior loop?

Am I missing something?

  • Comment on Declaration with conditional assignment not initializing loop local variable
  • Download Code

Replies are listed 'Best First'.
Re: Declaration with conditional assignment not initializing loop local variable
by Fletch (Bishop) on Jul 30, 2008 at 18:39 UTC

    Yes, the note in perlsyn advising against trying to use this construct:

           NOTE: The behaviour of a "my" statement modified with a statement
           modifier conditional or loop construct (e.g. "my $x if ...") is
           undefined.  The value of the "my" variable may be "undef", any
           previously assigned value, or possibly anything else.  Don't rely on
           it.  Future versions of perl might do something different from the
           version of perl you try it out on.  Here be dragons.
    

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      Ah, thanks. Documented => true. My apologies for missing that.