inq123 has asked for the wisdom of the Perl Monks concerning the following question:
Basically the symptom is that first I create a hash of hash of hash, then use a while(my ($key, $value) = each %hash) to loop through it, then inside the while loops, use 'last;' to break them. After that, create a second set of those while loops, and the problem is, the 2nd set of the while loops won't be entered. If I don't use 'last;', or if I use 'for my $key (keys %hash)', or if I use a dump immediately before the 2nd set of the while loops, the problem would be "fixed".
But I want to understand why the 2nd set of while loops do not work in the first place. Anyone could help? BTW I tested it on Perl on UNIX and Windows, 5.6.1 - 5.8.5.
Without further ado, here's the script:
use strict; use Dumpvalue; my %test = ('level1' => { 'level2' => { 'level3' => { 'level4' => 1} } + } ); #Dumpvalue->new->dumpValue(\%test); # when uncommented, this dump ## doesn't help the troubled while loops my $createtrouble = 1; if($createtrouble) { ################################################### # the woes of the troubled while loops further below is # really caused by the 'last's in these while loops while(my ($key1, $sdata) = each %test) { while(my ($key2, $stats) = each %$sdata) { last; } last; } } #Dumpvalue->new->dumpValue(\%test); # when uncommented, this dump ## mysteriously helps the troubled while loops print "Start print out now\n\n"; my $usewhile = 1; if($usewhile) { ################################################# # the troubled while loops while(my ($key1, $sdata) = each %test) { print "got in the first one!\n"; while(my ($key2, $stats) = each %$sdata) { print "got here! key2 is $key2\n"; } } } else { ################################################# # this one always works for my $key1 (keys %test) { my $sdata = $test{$key1}; print "got in the first one!\n"; for my $key2 (keys %$sdata) { print "got here! key2 is $key2\n"; } } }
2005-10-01 Retitled by planetscape, as per Monastery guidelines
Original title: 'A myterious bug that arises under certain innocent-looking situation'
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: mystery re each + last
by merlyn (Sage) on Sep 28, 2005 at 15:08 UTC | |
by inq123 (Sexton) on Sep 28, 2005 at 15:49 UTC | |
by radiantmatrix (Parson) on Sep 28, 2005 at 15:20 UTC | |
by inq123 (Sexton) on Sep 28, 2005 at 15:21 UTC | |
by merlyn (Sage) on Sep 28, 2005 at 16:26 UTC |