Chapter 2. Using the Building Blocks Control Constructs

In this chapter, we will cover:

  • Looping with if
  • Looping with for
  • Looping with foreach
  • Looping with while
  • Continuing a procedure
  • Breaking out of a procedure
  • Nested looping

Introduction

Control constructs are the building blocks of an action. In this chapter, we will explore the creation of procedures, as well as managing the flow of events.

Prior to the creation of constructs the programmer's primary tool was the goto statement. While this allowed recursive handling of conditions and minimized impact on memory usage, it resulted in non-modular code and added substantially to the overhead of debugging and maintenance.

In Tcl, as in all programming languages, a control construct is a command that instructs the program to perform a certain action (or actions) based on a predefined condition. How many times the action (or actions) is/are performed is based on the specific construct used. For example, an if statement will perform the pre-defined actions once, whereas a while statement will perform the actions until the condition is no longer met.

Tcl has a full contingent of control constructs. The basic usages or descriptions of these commands are as follows:

  • if

    The syntax for if command is as follows:

    if [condition 1] then [body1] elseif [condition 2] else [body2]
    

    Multiple elseif and then statements may be added as required.

  • for

    The syntax for the for command is as follows:

    for [start] [test] (next) [body]
    
  • foreach

    The syntax for the foreach command is as follows:

    foreach [varlist] [valuelist] [action]
    
  • while

    The syntax for while command is as follows:

    while [condition] [action]
    
  • continue

    Typically, the continue command is invoked from within the body of a control construct such as a for, foreach, or while. The continue command stops processing the current action and proceeds to the next iteration of the containing construct.

  • break

    Typically, the break command is invoked from within the body of a control construct such as a for, foreach, or while. The break command terminates processing of the script out to the innermost containing loop of the construct.

In the following examples, I will discuss the various control constructs in detail. To illustrate the differences better, all of the examples—with the exception of the if command—will result in similar, and in many cases, an identical output. This was done to demonstrate how the constructs interact with the values provided. To complete each of the following examples, you will need to create a Tcl script file in your working directory. To accomplish this, you will open the text editor of your choice and follow the instructions in each section.

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

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