This chapter describes the Tcl commands that implement control structures: if, switch, foreach, while, for, break, continue, catch, error, and return. Control structure in Tcl is achieved with commands, just like everything else. There are looping commands: while, foreach, and for. There are conditional commands: if and switch. There is an error handling command: catch. Finally, there are some commands to fine-tune control structures: break, continue, return, and error. A control structure command often has a command body that is executed later, either conditionally or in a loop. In this case, it is important to group the command body with curly braces to avoid substitutions at the time the control structure command is invoked. Group with braces, and let the control structure command trigger evaluation at the proper time. A control structure command returns the value of the last command it chose to execute. Another pleasant property of curly braces is that they group things together while including newlines. The examples use braces in a way that is both readable and convenient for extending the control structure commands across multiple lines. Commands like if, for, and while involve boolean expressions. They use the expr command internally, so there is no need for you to invoke expr explicitly to evaluate their boolean test expressions. |