While

   

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 6.  Control Structure Commands


While

The while command takes two arguments, a test and a command body:

 while booleanExpr body 

The while command repeatedly tests the boolean expression and then executes the body if the expression is true (nonzero). Because the test expression is evaluated again before each iteration of the loop, it is crucial to protect the expression from any substitutions before the while command is invoked. The following is an infinite loop (see also Example 1-13 on page 12):

 set i 0 ; while $i<10 {incr i} 

The following behaves as expected:

 set i 0 ; while {$i<10} {incr i} 

It is also possible to put nested commands in the boolean expression. The following example uses gets to read standard input. The gets command returns the number of characters read, returning -1 upon end of file. Each time through the loop, the variable line contains the next line in the file:

Example 6-7 A while loop to read standard input.
 set numLines 0 ; set numChars 0 while {[gets stdin line] >= 0} {    incr numLines    incr numChars [string length $line] } 

       
    Top
     



    Practical Programming in Tcl and Tk
    Practical Programming in Tcl and Tk (4th Edition)
    ISBN: 0130385603
    EAN: 2147483647
    Year: 1999
    Pages: 478

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net