http://qs321.pair.com?node_id=11120537


in reply to Not understanding while loop counting

The condition is evaluated before the loop body is executed, and more importantly, you're printing the value immediately after incrementing it, so the condition has no way of being checked after the increment from 9 to 10. Perhaps you need to change the order of the statements, and/or maybe you're thinking of do { ... } while ... (perlsyn)?

Update: Here's another way to think about it. Every loop can be reduced to a while (true) {...} with a conditional break out of the loop at the appropriate point (and if you want to go even further, you can try unrolling that loop in your head, i.e. think about the order of the operations if there was no loop and the statements were simply repeated Update 2: as davido showed).

my $count = 0; print "entering loop with count=$count\n"; while (1) { print "before testing, count=$count\n"; last unless $count < 10; print "before incrementing, count=$count\n"; $count += 1; print "count is now $count\n"; } print "exited loop with count=$count\n";

Update 3: I've now modified the code example to insert lots of debugging prints (see also the Basic debugging checklist) and to fix a logic bug (I had forgotten to invert the condition).