Introducing Tcl

Introducing Tcl

The creator of Tcl, John Ousterhout, intended it to be a simple, embeddable scripting language whose interpreter could be linked with any C program, so that the C program could use Tcl scripts. The term embeddable refers to this property of Tcl-the capability of any C program to use the Tcl interpreter and run Tcl scripts.

John Ousterhout created Tcl and Tk when he was at the University of California at Berkeley. Tcl first appeared in 1989; Tk followed in 1991. Tcl/Tk are freely available for unrestricted use, including commercial use. At the time of this writing, the current Tcl version is 8.3; Tk is also 8.3. Red Hat Linux comes with Tcl/Tk.

The following sections provide an overview of Tcl, its syntax, and some of its important commands. Because Tcl underlies the Tk toolkit, you should become familiar with Tcl before jumping into Tk, although Tk undoubtedly is more fun because you can use it to create graphical interfaces.

Writing Your First Tcl Script

In Chapter 24, you learned how to write shell scripts and Perl scripts. You write Tcl scripts the same way. Unlike Perl, Tcl includes a shell-an interactive interpreter of Tcl commands. The Tcl shell program's name is tclsh; it should be in the /usr/bin directory.

When you log in, the PATH environment variable should include the /usr/bin directory. Thus, you can start the Tcl shell by typing tclsh at a text console or in a terminal window in GNOME or KDE. A percent sign (%) appears on the next line; this is the Tcl shell program's prompt. To see which version of Tcl you have, type info tclversion at the Tcl shell prompt. The Tcl shell program responds by printing the version of Tcl. Here is an example of how you interact with the Tcl shell:

% info tclversion

Now you can interactively try the following Tcl program, which prints Hello, World! on the standard output (the display screen or the terminal window):

% puts "Hello, World!"
Hello, World!
% exit

Type exit to quit the Tcl shell.


Note that I don't show the shell prompt in previous chapters, but I show the Tcl prompt (%) in many of this chapter's code listings. That's because the Tcl prompt looks different from the Bash prompt, which should tell you that you aren't working in Bash.

The Tcl shell immediately processes the Tcl command you enter and displays the results, then it prompts you for the next input. At this point, you can type exit to quit the Tcl shell (tclsh).

To prepare and run a Tcl script, follow these steps:

  1. Use a text editor to enter and save the following lines in a file named hellotcl (this file will be the Tcl script):

    # A simple Tcl script
    puts "Hello, World!"
  2. Type the following command at the shell prompt to make the hellotcl file executable (that's what the +x in the chmod command means):

    chmod +x hellotcl
  3. To run the hellotcl script, type the following at the shell prompt:

    Hello, World!

Use these basic steps to create and run any Tcl script. You still have to learn the nuances of Tcl syntax, of course-as well as many rules. This section gets you started with an overview of Tcl.

Getting More Information on Tcl/Tk

This chapter provides an overview of Tcl and Tk, highlights many key points, and shows simple examples. However, there isn't enough room in this chapter to list all the information you need to fully exploit the power of Tcl and Tk. Because of Tcl/Tk's popularity, you can find quite a few resources about it, ranging from books to Internet sites. Following is a short list of Tcl/Tk resources:

  • Books -Two prominent books on Tcl/Tk are available. The first book is Tcl and the Tk Toolkit (Addison Wesley 1994) by John K. Ousterhout, the originator of Tcl and Tk. John's book provides a broad overview of Tcl and Tk, including an explanation of the way that Tcl command strings are parsed. The other book is Practical Programming in Tcl and Tk, Third Edition (Prentice Hall 2000) by Brent B. Welch. This book provides more Tcl and Tk examples.

  • Internet resources-Several FTP and websites contain the latest Tcl/Tk distributions and information about Tcl/Tk development. Following are the URLs for a few key sites:

    • master distribution site)

    • developer site)

    • contributed sources archive)

Getting an Overview of Tcl

True to its name (Tool Command Language), Tcl consists of a set of commands you can combine according to a set of rules. To write Tcl scripts, you have to understand two broad subjects:

  • Tcl syntax-Tcl syntax is the set of rules the Tcl command interpreter follows when it interprets a command string (a line that contains a command and its arguments).

  • Tcl commands-Although the syntax is the same for all commands, each Tcl command is meant to perform a specific task. To exploit Tcl fully, you have to know what commands are available and what each command does. The Tcl command set can be extended by applications. In fact, Tk itself is an extension of Tcl; Tk adds commands that manipulate components of GUIs.

Start by learning the Tcl syntax, a handful of rules that determine the way each Tcl command is parsed. Because Tcl has many commands, learning all of them can take a while. Even after you become proficient in the Tcl syntax and a small set of commands, you may need to keep a reference manual nearby so that you can check the exact format of the arguments that each command requires.

Tcl commands include the following basic programming facilities that you expect from any programming language:

  • Variables, which store data. Each variable has a name and a value. Tcl also allows you to define arrays of variables.

  • Expressions, which combine values of variables with operators. An expression might add two variables, for example. Tcl uses the expr command to evaluate expressions.

  • Control-flow commands, which enable commands to be executed in various orders, depending on the value of some expression. Tcl provides commands such as for, foreach, break, continue, if, while, and return to implement flow control in Tcl scripts.

  • Procedures, which enable you to group several commands and give them a name. Procedures also accept arguments. Tcl provides the proc command to enable you to define procedures. You can use a procedure to execute the same set of commands (usually with different arguments) by invoking the procedure that represents those commands.

The next few sections provide an overview of the Tcl syntax and the core Tcl commands.

Learning the Basic Tcl Syntax

To understand the basic Tcl syntax, you have to know a bit about how the Tcl interpreter processes each command string. The steps are as follows:

  1. The Tcl interpreter parses (breaks down) the command string into words-the constituent parts, including variables and operators.

  2. The Tcl interpreter applies rules to substitute the values of variables and replace certain commands with their results.

  3. The Tcl interpreter executes the commands, taking the first word as the command name and calling a command procedure to execute the command. The command procedure receives the rest of the words as strings.

When writing Tcl command strings, you have to use white space (a space or a tab) to separate a command's name from its arguments. A newline or a semicolon (;) marks the end of a command string. You can put two commands on the same line if you insert a semicolon after the first command. Thus, you can use the following:

% puts Hello, ; puts World!

The resulting output appears on separate lines because the puts command adds a newline by default.

Use a backslash (\) at the end of a line to continue that command string on the next line (this is a standard convention in UNIX). Thus, you can write a command string to print Hello, World! as follows:

puts "Hello, \


The Tcl interpreter replaces certain parts of the command string with an equivalent value. If you precede a variable's name with a dollar sign ($), for example, the interpreter replaces that word with the variable's value. As you learn in the 'Variables' section, you can define a variable in a Tcl script by using the set command, as follows:

set count 100

This command defines a variable named count with the value 100. Suppose that you type the following:

puts $count

The interpreter first replaces $count with its value, 100. Thus, that command string becomes:

puts 100

When the interpreter executes the puts command, it prints 100. This is an example of variable substitution.

In all, the Tcl interpreter supports three kinds of substitutions:

  • Variable substitution-As the preceding example shows, if the Tcl interpreter finds a dollar sign ($), it replaces the dollar sign as well as the following variable name with that variable's value.

  • Backslash substitution-You can embed special characters, such as the newline and tab, in a word by using backslash substitution. Type a backslash, followed by one or more characters; the interpreter replaces that sequence with a nonprintable character. These sequences are patterned after ANSI Standard C's escape sequences. Table 25-1, which follows this list, summarizes the backslash sequences that the Tcl interpreter understands.

  • Command substitution-This type of substitution refers to the mechanism that enables you to specify that a command be evaluated and replaced by its result before the interpreter processes the command string. The command string length "Hello, World!", for example, returns 13, the length of the string. To set a variable named len to the length of this string, type the following:

    set len [string length "Hello, World!"]

    The interpreter processes the command inside the square brackets and replaces that part of the command string with the value of the command. Thus, this command becomes

    set len 13

    and the set command sets the len variable to 13.

    Table 25-1: Backslash Sequences and Their Meanings in Tcl


    Replacement Character *


    Bell character (0x7)


    Backspace (0x8)


    Form feed (0xc)


    Newline (0xa)


    Carriage return (0xd)


    Horizontal tab (0x9)


    Vertical tab (0xb)


    Replace the newline and white space on the next line with a single space


    Interpret as a single backslash (\)


    Interpret as double quotation marks (")


    Use the value specified by the octal digits ooo (up to three)


    Use the value specified by the hexadecimal digits hh (up to two)

* Hexadecimal values are shown in parentheses (for example, 0xd means hexadecimal d)


A pound sign (#) marks the start of a comment; the Tcl interpreter disregards the rest of the line, beginning with the pound sign. Tcl does, however, have a peculiar requirement for comments: you cannot start a comment within a command. The command string must end before you start a comment.

To understand this problem, try the following Tcl command at the tclsh prompt:

% puts "Hello, World!" # This is a comment
wrong # args: should be "puts ?-nonewline? ?channelId? string"

Essentially, the puts command processes the remainder of the line and complains about the number of arguments. The solution is to put a semicolon just before the pound sign (#), as follows:

% puts "Hello, World!" ;# This is a comment
Hello, World!
Insider Insight 

If you put comments at the end of a Tcl command, remember to precede the pound sign (#) with a semicolon (;). The semicolon terminates the preceding command and enables you to start a comment.

Braces and Double Quotation Marks

You can use braces ({...}) and double quotation marks ("...") to group several words. Use double quotes to pass arguments that contain an embedded space or a semicolon, which otherwise ends the command. The quotes are not part of the group of words; they simply serve to mark the beginning and end of a group of words. Following are some examples of using double quotes to group words:

% puts "Hello, World!"
Hello, World!
% puts "Enter 1; otherwise file won't be saved!"
Enter 1; otherwise file won't be saved!

When you group words with double quotes, all types of substitutions still take place, as the following example illustrates:

% puts "There are [string length hello] characters in 'hello'"
There are 5 characters in 'hello'

The Tcl interpreter replaces everything inside the brackets with the result of the string length hello command, whose return value is the number of characters in hello (5). In the expression [string length hello], you can replace the string hello with any variable to determine the length of that variable's value.

Also, you can use braces to group words. The Tcl interpreter does not perform any substitutions when you group words with braces (if you enclose words in double quotes, the interpreter does perform a substitution). Consider the preceding example with braces instead of double quotes:

% puts {There are [string length hello] characters in 'hello'}
There are [string length hello] characters in 'hello'

As the result shows, the Tcl interpreter simply passes everything, unchanged, as a single argument.

Insider Insight 

Use braces as a grouping mechanism when you have to pass expressions to control commands, such as while loops, for loops, or procedures.

Understanding Tcl Variables

Everything is a string in Tcl. Variable names, as well as values, are stored as strings. To define a variable, use the built-in Tcl command set. The following commands, for example, define the variable book as "Red Hat Linux Professional Secrets"; the variable year as 2003; and the variable price as $49.99:

set book "Red Hat Linux Professional Secrets"
set year 2003
set price \$49.99

To refer to the value of a variable, add a dollar sign ($) prefix to the variable's name. Therefore, to print the variable book, use the following format:

% puts $book
Red Hat Linux Professional Secrets

If you use set with a single argument, set returns the value of that argument. Thus, set book is equivalent to $book, as the following example shows:

% puts [set book]
Red Hat Linux Professional Secrets

Writing Expressions

You can write expressions by combining variables with mathematical operators, such as + (add), - (subtract), * (multiply), and / (divide). Here are some examples of expressions:

set count 1
$count + 5 - 2
2 + 3.5

You can use numbers, as well as variable names, in expressions. Use white space to enhance readability. Use parentheses to specify how you want an expression to be evaluated.

In addition to the basic mathematical operators, Tcl includes several built-in mathematical functions, such as sin, cos, tan, log, and sqrt. Call these functions just as you do in C, with arguments in parentheses, as follows:

set angle 1.5

In addition, you can use Boolean operators, such as ! (not), && (and), and || (or). Comparison operators-such as < (less than), > (greater than), <= (less than or equal to), == (equal to), and != (not equal to)-also are available. Expressions that use Boolean or comparison operators evaluate to 1 if true and 0 if false. You can write expressions, such as the following:

count == 10
angle < 3.1415

Expressions are not commands by themselves. You can use expressions as arguments only for commands that accept expressions as arguments. The if and while commands, for example, expect expressions as arguments.

Tcl also provides the expr command to evaluate an expression. The following example shows how you might evaluate an expression in a Tcl command:

% set angle 1.5
% puts "Result = [expr 2*sin($angle)]"
Result = 1.99498997321

Although Tcl stores everything as a string, you have to use numbers where numbers are expected. If book is defined as "Red Hat Linux Professional Secrets", for example, you cannot write an expression $book+1, because it does not make sense.

Using Control-Flow Commands in Tcl

Tcl's control-flow commands enable you to specify the order in which the Tcl interpreter executes commands. You can use the if command to test the value of an expression; and if the value is true (nonzero), you can make the interpreter execute a set of commands. Tcl includes control-flow commands similar to those in C, such as if, for, while, and switch. This section provides an overview of the control-flow commands.

Using the if Command

In its simplest form, Tcl's if command evaluates an expression and executes a set of commands if that expression is nonzero (true). You might compare the value of a variable with a threshold as follows:

if { $errorCount > 25 } {
    puts "Too many errors!"

You can add an else clause to process commands if the expression evaluates to zero (false). Following is an example:

if { $user == "root" } {
    puts "Starting system setup ..."
} else {
    puts "Sorry, you must be \"root\" to run this program!"

Tcl's if command can be followed by zero or more elseif commands if you need to perform more complicated tests, such as the following:

puts -nonewline "Enter version number: "  ;# Prompt user
set version [gets stdin]                  ;# Read version number

if { $version >= 10 } {
   puts "No upgrade necessary"
} elseif { $version >= 6 && $version < 9} {
   puts "Standard upgrade"
} elseif { $version >= 3 && $version < 6} {
    puts "Reinstall"
} else {
    puts "Sorry, cannot upgrade"

Using the while Command

The while command executes a block of commands until an expression becomes false. The following while loop keeps reading lines from the standard input until the user presses Ctrl+D:

while { [gets stdin line]  != -1 } {
    puts $line
# Do whatever you need to do with $line.

Although this while command looks simple, you should realize that it has two arguments inside two sets of braces. The first argument is the expression; the second argument contains the Tcl commands to be executed if the expression is true. You must always use braces to enclose both of these arguments. The braces prevent the Tcl interpreter from evaluating the contents; the while command is the one that processes what's inside the braces.

If you use a variable to keep count inside a while loop, you can use the incr command to increment that variable. You can skip to the end of a loop by using the continue command; the break command exits the loop. The following Tcl script uses a while loop to add all the numbers from 1 to 10, except 5:


set i 0
set sum 0

while { 1 } {
    incr i                     ;# Increment i
    if {$i == 5} { continue }  ;# Skip if i is 5
    if {$i > 10} {break }      ;# End loop if i exceeds 10
    set sum [expr $sum+$i]     ;# Otherwise, add i to sum
puts "Sum = $sum";

When you run this script, it should display the following result:

Sum = 50

Using the for Command

Tcl's for command takes four arguments, which you should type in the following manner:

for {expr1} { expr2} { expr3} {

The for command evaluates expr1 once at the beginning of the loop and executes the commands inside the final pair of braces, until the expression expr2 evaluates to zero. The for command evaluates the third expression-expr3-after each execution of the commands. You can omit any of the expressions, but you must use all the braces. The following example uses a for loop to add the numbers from 1 to 10:

for {set i 0; set sum 0} {$i <= 10} {set sum [expr $sum+$i]; incr i} {
puts "Sum = $sum";

When you run this script, it displays the following result:

Sum = 55

Using the foreach Command

You have not seen a command like foreach in C, but foreach is handy when you want to perform some action for each value in a list of variables. You can add a set of numbers with the foreach command as follows:

set sum 0
foreach i { 1 2 3 4 5 6 7 8 9 10} {
    set sum [expr $sum+$i]
puts "Sum = $sum"

When you run this script, this one also prints Sum = 55 because the script is adding the numbers 1 through 10.

If you have a list in a variable, you can use that variable's value in place of the list shown within the first pair of braces. Following is a foreach loop that echoes the strings in a list:

set users "root naba"
foreach user $users {
    puts "$user"

Using the switch Command

Tcl's switch command is different from C's switch statement. Instead of evaluating a mathematical expression, Tcl's switch command compares a string with a set of patterns and executes a set of commands, depending on which pattern matches. Often, the pattern is expressed in terms of a regular expression.

Cross Ref 

See Chapter 24 for an introduction to regular expressions.

The following script illustrates the syntax and a typical use of the switch command:

# This script reads commands from the user and processes
# the commands using a switch statement.

set prompt "Enter command (\"quit\" to exit): "

puts -nonewline "$prompt"; flush stdout

while { [gets stdin cmd]  != -1 } {
    switch -exact -- $cmd {
        quit    { puts "Bye!"; exit}
        start   { puts "Started"}
        stop    { puts "Stopped"}
        draw    { puts "Draw.."}
        default { puts "Unknown command: $cmd" }
# Prompt user again
    puts -nonewline $prompt; flush stdout

Following is a sample session with this script (user input is in boldface):

Enter command ("quit" to exit): help
Unknown command: help
Enter command ("quit" to exit): start
Enter command ("quit" to exit): stop
Enter command ("quit" to exit): quit

As this example shows, the switch statement enables you to compare a string with a set of other strings and to activate a set of commands, depending on which pattern matches. In this example, the string is $cmd (which is initialized by reading the user's input with a gets command), and the patterns are literal strings: quit, start, stop, and draw.

Writing Tcl Procedures

You can use the proc command to add your own commands. Such commands are called procedures; the Tcl interpreter treats them just as though they were built-in Tcl commands. The following example shows how easy it is to write a procedure in Tcl:


proc total items {
    set sum 0
    foreach i $items {
        set sum [expr $sum+$i]
    return $sum

set counts "5 4 3 5"
puts "Total = [total $counts]"

When you run the preceding script, it prints the following:

Total = 17

In this example, the procedure's name is total, and it takes a list of numbers as the argument. The procedure receives the arguments in the variable named items. The body of the procedure extracts each item and returns a sum of the items. Thus, to add numbers from 1 to 10, you have to call the total procedure as follows:

set sum1_10 [total {1 2 3 4 5 6 7 8 9 10}]

If you want to access a global variable (a variable defined outside a procedure) in the Tcl procedure, you have to use the global command inside the procedure. The global command makes a global variable visible within the scope of a procedure. If a variable named theCanvas holds the current drawing area in a Tk (Tcl's X toolkit) program, a procedure that uses theCanvas must include the following command:

global theCanvas

Taking Stock of Built-in Tcl Commands

You have seen many Tcl commands in the preceding examples. Knowing the types of commands that are available in Tcl helps you decide which commands are most appropriate for the task at hand. Although this chapter does not have enough room to cover all Tcl commands, Table 25-2 summarizes Tcl's built-in commands.

Insider Insight 

To get online help about any Tcl command listed in Table 25-2, type man n, followed by the command name. To get online help about Tcl's file command, for example, type man n file.

Table 25-2: Built-in Tcl Commands




Appends an argument to a variable's value


Performs various operations on an array variable


Exits a loop command (such as while and for)


Executes a script and traps errors to prevent errors from reaching the Tcl interpreter


Changes the current working directory


Closes an open file


Joins two or more lists in a single list


Immediately begins the next iteration of a for or while loop


Checks to see whether end-of-file is reached in an open file


Generates an error


Concatenates lists (as concat does), and then evaluates the resulting list as a Tcl script


Starts one or more processes that execute the command's arguments


Terminates the Tcl script


Evaluates an expression


Checks filenames and attributes


Flushes buffered output to a file


Implements a for loop


Performs a specified action for each element in a list


Formats output and stores it in a string (as the sprintf function in C does)


Reads a line from a file


Returns the names of files that match a pattern (such as *.tcl)


Accesses global variables


Provides access to the history list (the list of past Tcl commands)


Tests an expression and executes commands if the expression is true (nonzero)


Increments the value of a variable


Returns internal information about the Tcl interpreter


Creates a string, by joining all items in a list


Appends elements to a list


Returns an element from a list at a specified index. (Index 0 refers to the first element.)


Inserts elements into a list before a specified index


Creates a list composed of the specified arguments


Returns the number of elements in a list


Returns a specified range of adjacent elements from a list


Replaces elements in a list with new elements


Searches a list for a particular element


Sorts a list in a specified order


Opens a file and returns a file identifier


Returns the process identifier (ID)


Defines a Tcl procedure


Sends characters to a file


Returns the current working directory


Reads a specified number of bytes from a file. (You can read the entire file in a single read.)


Matches a regular expression with a string


Substitutes one regular expression pattern for another


Renames or deletes a command


Returns a value from a Tcl procedure


Parses a string, using format specifiers patterned after C's sscanf function


Changes the access position (where the next input or output operation occurs) in an open file


Sets a variable's value or returns its current value


Reads a file and processes it as a Tcl script


Breaks a string into a Tcl list


Performs various operations on strings


Processes one of several blocks of commands, depending on which pattern matches a specified string


Returns the current access position for an open file


Returns the total time needed to execute a script


Executes a specified set of Tcl commands whenever a variable is accessed


Handles any unknown command. (The Tcl interpreter calls this command whenever it encounters any unknown command.)


Removes the definition of one or more variables


Executes a script in a different context


References a variable outside a procedure. (This is used to implement the pass-by-reference style of procedure call, in which changing a procedure argument changes the original copy of the argument.)


Implements a while loop that executes a set of Tcl commands repeatedly, as long as an expression evaluates to a nonzero value (true)

Manipulating Strings in Tcl

If you browse through the Tcl commands listed in Table 25-2, you find quite a few-such as append, join, split, string, regexp, and regsub-that operate on strings. This section summarizes a few string-manipulation commands.

The join command is the opposite of split; you can use it to create a single string from the items in a list. Suppose that you have a list of six items, defined as follows:

set x {1 2 3 4 5 6}

When you join the elements, you can select what character you want to use between fields. To join the elements without anything in between them, use the following format:

set y [join $x ""]

Now the y string is "123456".

The string command is a group of commands for working with strings; the first argument of string specifies the operation to be performed. The string compare command, for example, compares two strings, returning zero when the two strings are identical. A return value of -1 indicates that the first string argument is lexicographically less than the second one, which means it appears before the second one in a dictionary. Similarly, a 1 return value indicates that the first string is lexicographically greater than the second one. Thus, you might use string compare in an if command as follows:

if { [string compare $command "quit"] == 0} {
    puts "Exiting..."
    exit 0

Table 25-3 lists the