tcl Control Structures if / while / for


Example

if expr1 ?then? body1 elseif expr2 ?then? body2 ... ?else? ?bodyN?

exprN is an expression that evaluates to a boolean value. bodyN is a list of commands.

set i 5
if {$i < 10} {
  puts {hello world}
} elseif {$i < 70} {
  puts {enjoy world}
} else {
  puts {goodbye world}
}

for start test next body

start, next and body are lists of commands. test is an expression that evaluates to a boolean values.

The break command will break out of the loop. The continue command will skip to the next iteration of the loop.

The common usage is:

for {set i 0} {$i < 5} {incr i} {
  puts "$i: hello world"
}

Since start and next are lists of commands, any command may be present.

for {set i 0; set j 5} {$i < 5} {incr i; incr j -1} {
  puts "i:$i j:$j"
}

while test body

The test is any expression that evaluates to a boolean value. While test is true, body is executed.

set x 0
while {$x < 5} {
  puts "hello world"
  incr x
}

The break command will break out of the loop. The continue command will skip to the next iteration of the loop.

set lineCount 0
while {[gets stdin line] >= 0} {
  puts "[incr lineCount]: $line"
  if { $line eq "exit" } {
    break
  }  
}