Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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


In reply to Re: Not understanding while loop counting (updated!) by haukex
in thread Not understanding while loop counting by zapdos

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

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

    No recent polls found