Looping with for

The for command performs the actions desired as long as the condition is met. In this manner the condition is repeatedly evaluated and the actions are performed as long as the condition remains true. The syntax of the for statement consists of three arguments (start, test, and next) and a body:

for start test next body

The start, next, and the body arguments must be in the form of Tcl command strings with test as an expression string. The for command invokes the interpreter to execute start. Then, it repeatedly evaluates test as an expression. While the result is non-zero, it invokes the Tcl interpreter on body. Then, it invokes the interpreter on next and repeats the loop. The command terminates when test is evaluated to 0.

Please note that the condition should always be enclosed within braces to avoid command substitution prior to processing, which may result in the dreaded infinite loop.

How to do it…

In the following recipe, we will create a Tcl script to be called from the command line that increments the value of x and prints out the value.

Create a text file named for.tcl that contains the following commands.

# While x is less than 11 print out the value of x
for {set x 1} {$x < 11} {incr x} {
	puts "x = $x"
}

Now invoke the script using the following command line:


tclsh85 for.tcl
x = 1
x = 2
x = 3
x = 4
x = 5
x = 6
x = 7
x = 8
x = 9
x = 10

How it works…

As you can see, the action was invoked multiple times while the condition remained true. As we wanted to start at 1 and print out up to 10, the condition was set to be true while x was less than 11. This could have been done by setting the condition to <=10 (less than or equal to 10) as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.246.148