Control Flow

  • The structures are similar to C and UNIX csh shell
  • They are implemented as commands, as any other thing in Tcl
  • Remember: Tcl needs a space to tell one argument from another
  • Braces are NOT separators (as in C and Perl)
for init test reinit body
  • Similar to the C and Perl implementation
  • All the arguments are normal Tcl scripts
  • The for command returns an empty string as the result
Example:
% for {set i 1} {$i<=10} {incr i} { puts -nonewline "$i," }
1,2,3,4,5,6,7,8,9,10,
% set n 5
% for {set res 1; set i $n} {$i>1} {incr i -1} { 
        set res [expr $res*$i] 
}
% puts $res
120                                                  ;# 5! = 120
foreach varName list body
  • Basic form
  • Iterates over all the elements of the list
  • While executing the body, the current element is stored in the variable varName
Example:
% set cirFiles {bjtnoise mos6inv rca3040 schmitt}
% foreach c $cirFiles {
    runspice $c.cir
}
foreach varList1 valList1 [varList2 valList2 ...] body
See TCL book for a full explanation.
while test body
  • Evaluate the test script as an expression
  • Executes the body script if it's nonzero and then ...
  • ... re-evaluate the test and loop
  • Returns an empty string
Example:
set done 0
while {!$done} {                          ;# "while \{!$done\}\{" is wrong! 
    set done [do_task]                    ;# Put a space between \} and \{
}

set fp [open $filename]
while { [gets $fp line] != -1 } {
    puts "I've read : $line"
}
if test1 body1 [elseif test2 body2 ... else bodyn]
  • Evaluate the test1 script as an expression
  • If it's nonzero executes the body1 script and returns its value, otherwise ...
  • ... evaluates the test2 script
  • ... and so on...
Example:
if { $name != $entryname } {                ;# note the != between strings
    vhs_parse_to_endl skip $fp
} else {                                    ;# remember the spaces!
    vhs_parse_to_endl doit $fp
}
switch [options] string { pattern body [pattern body...] }
  • Matches string against each pattern in order, until a match is found
  • Executes the corresponding body and returns its value
  • Doesn't keep on matching, as in C/C++
  • If the last pattern is ``default'', it matches any value
  • If a body is - then Tcl uses the body of the next pattern
  • Options are -exact, -glob, -regexp and --
  • Use -- to tell that the next argument is the string, even if it begins with a dash (-)
Example:
switch -- $arg {
    "-d" { VovOutput "$FILEPREFIX.tab.h"  }
    "-l" -
    "-r" {}
    "-b" { set FILEPREFIX [shift] }
    "-v" { 
        if { [file tail $argv0] == "byacc" } {
            VovOutput "$FILEPREFIX.code.c" 
        } else {
            VovOutput "$FILEPREFIX.output" 
        }
    }
    default {
        VovFatalError "Unknown option $arg" 
    }
}