TCL Control Flow Commands

Tcl's control flow commands resemble those found in languages such as C, csh, and Perl. These include commands like if, while, for, foreach, and switch.

The if Command

The if command evaluates an expression, tests its result, and conditionally executes a script based on the outcome. It can include multiple elseif clauses and a final else clause.

if {$y < 0} {
      ...
  } elseif {$y == 1} {
      ...
  } else {
      ...
  }

Looping Commands

Tcl provides three commands for looping: while, for, and foreach. These commands facilitate repetitive tasks.

The while Command

The while command continuously evaluates an expression and executes a script as long as the expression is true.

set b ""
    set i [expr [llength $a] - 1]
    while {$i >= 0} {
        lappend b [lindex $a $i]
        incr i -1
    }

The for Command

The for command is similar to while but provides more explicit loop control.

set b ""
for {set j [expr [llength $a] - 1]} {$j >= 0} {incr j -1} {
    lappend b [lindex $a $j]
}

The foreach Command

The foreach command iterates over all elements of a list, executing a script for each element.

set b ""
foreach k $a {
    set b [linsert $b 0 $k]
}

Loop Control: break and continue

The break command terminates the innermost loop immediately, while continue stops the current iteration and proceeds to the next one.

set b ""
foreach l $a {
    if {$l == "ZZZ"} break
    set b [linsert $b 0 $l]
}
set b ""
foreach m $a {
    if {$m == "ZZZ"} continue
    set b [linsert $b 0 $m]
}

The switch Command

The switch command tests a value against multiple patterns, executing a corresponding script based on the match.

switch $x {
    "a" {incr t1}
    "b" {incr t2}
    "c" {incr t3}
}

The eval Command

The eval command concatenates arguments and executes them as a Tcl script, providing a way to generate and run commands dynamically.

set cmd "set z 0"
...
eval $cmd

The source Command

The source command reads a file and executes its content as a Tcl script.

source init.tcl

Exercise

Write a program that asks the user for the outside temperature in degrees Celsius, converts it to Fahrenheit, and provides advice based on the temperature.

puts "Enter the temperature in Celsius"
gets stdin tempC;
set tempF [expr (($tempC * 9 / 5) + 32)]
puts "$tempC degrees Celsius is $tempF degrees Fahrenheit"
if {$tempF < 40} {
    puts "Temperature is very low. Please take a coat"
} elseif {$tempF > 80} {
    puts "Temperature is very hot. Don't go out. Avoid sunburns"
} else {
    puts "Have a great day!"
}
© 2025 semihub.in. All rights reserved.