Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Not understanding while loop counting (updated!)

by haukex (Archbishop)
on Aug 10, 2020 at 08:14 UTC ( [id://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?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (5)
As of 2024-04-19 15:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found