http://qs1969.pair.com?node_id=495783

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

Hi, yesterday I got a strange bug that took a while to fix. It also took a while to trace down the bug enough to recreate it in the short script below (original script was too long to post).

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'