justjohn has asked for the wisdom of the Perl Monks concerning the following question:
#!/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?
|
|---|
| 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 | |
by justjohn (Initiate) on Jul 30, 2008 at 20:06 UTC |