develooper Front page | perl.perl5.porters | Postings from December 2004

[perl #2215] redo undefines variables declared like while (my $i ...) { redo; }

Thread Previous
From:
Steve Peters via RT
Date:
December 7, 2004 19:50
Subject:
[perl #2215] redo undefines variables declared like while (my $i ...) { redo; }
Message ID:
rt-3.0.11-2215-102361.5.68536563332628@perl.org
> [khw@bighorn.dr.lucent.com - Fri Feb 25 02:35:04 2000]:
> 
> 
> This is a bug report for perl from khwilliamson@lucent.com,
> generated with the help of perlbug 1.26 running under perl 5.00503.
> 
> 
> -----------------------------------------------------------------
> The following program is an example:
> 
> use strict;
> my @A = ( 1, 2, 3);
> #my $i;
> while (my $i = shift @A) {
> 	print "i=$i\n";
> 	last unless defined $i;
> 	redo;
> }
> 
> Different results occur if $i is declared outside the while
> statement (it works) than as shown above.  The redo causes
> $i to become undefined.

This does not appear to be a bug.  Quoting "Programming Perl, Second
Edition", "The redo command restarts the loop block without evaluating
the conditional again."  So, when it re-enters the block, the shift is
not performed and $i is implicitly defined to undef and the previous
value is lost.  The correct thing to do is to declare the variable
outside of the loop conditional, or initialize $i within the block. 

 while (@A) {
    my $i = shift @A;
    print "i=$i\n";
    last unless defined $i;
    # redo; or just
}
> } 


Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About