Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re: Not understanding while loop counting (updated!)

by haukex (Bishop)
on Aug 10, 2020 at 08:14 UTC ( #11120537=note: print w/replies, xml ) Need Help??

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).

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11120537]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2021-05-13 19:01 GMT
Find Nodes?
    Voting Booth?
    Perl 7 will be out ...

    Results (140 votes). Check out past polls.