CS248 Menu Buttons

UNIX Programming

"Chapter Fourteen - Tcl: Tool Command Languge"

Chapter Outline

Lecture Notes

Tcl: Tool Command Languge

Tcl (pronounced tickle) has been developed by John Ousterhout and is a programming language for a diverse range of applications. here is what this chapter covers:

A Tcl Overview

We start with how to write and execute Tcl programs.

Our First Tcl Program

We start with a simple program, hello.tcl, that writes a very simple Hello World message.

Here's the source code for hello.tcl:

Tcl is an interpreted language and Tcl programs are often referred to as scripts.

Let's run the script using the tclsh shell.

Like other UNIX command interpreters, we can run tclsh abd it will prompt us for Tcl commands to execute immediately. For example, you could have typed in the commands:

The tclsh prompts with % and executes our commands immediately.

We can use the source command to make tclsh take command from a file.

The exit command causes the Tcl shell to end and returns us to the UNIX shell.

We can turn our script into a UNIX program by specifying the interpreter to use on the first line, as shown in the program hello2.tcl.

tclsh is generally installed in /usr/bin<./P>

You may have to change the mode of a file to make it executable. This is done with the chmod +x command.

Tcl Commands

Tcl commands all take the same form: they begin with a keyword and are followed by zero or more arguments.

Here is the general form of the tcl command notation we will use.

Variables and Values

Most values are dealt with as strings and, where necessary, Tcl will automatically convert between types.

To assign a variable and create it if necessary, use the set command.

Variable names can have white space, if the name is quoted.

To examine the current value of a variable, use the set command, but don't give it a value argument.

To use the value of a variable in another command we prefix its name with a $, much as we do in the UNIX shell.

We can remove a variable from the Tcl interpreter by using unset.

Quoting and Substitution

Quoting is crucial in Tcl and there are a number of different quoting and substitution mechanisms in Tcl.

Variable Substitution

In a Tcl command, a variable is replaced by its value whenever its name appears preceded by a dollar sign, $.

Command Substitution

A command containd within square brackets. [], is executed and replaced with its result.

Backslash Substitution

We use a backslash, \, to turn off the special meaning of the following character, such as a $.

A backslash at the end of a line is used as a continuation marker.

String Quoting

We use double quotes to create strings containing white space and other special characters.

Brace Quoting

Another form of quoting, using braces, {}, doesn't allow variable substitutions and cretes a verbatim group of strings.

The difference between joe and moe is that the variable subsititution in moe have been prevented by the braces.

When a group surrounded by braces is evaluated, the outermost set of brace are effectively removed.

Tcl Interpreter Substitution

Tcl always performs a single round of substitutions.

If the results contain further variable references or nested commands, these are not expanded.

We can gain additional rounds of substitutions using eval or explicitly by calling the subst command.

The difference is that the argument to eval must be a command, which is executed. subst performs substitution but doesn't evaluate the results.

The control of substitution and execution makes Tcl a very powerful tool.

Comments

Tcl comments start with what looks like the command #..


Calculation

The Tcl command for performing arithmetic calcuations is expr. It takes one or more arguements and calculates a result.

Examples are:

Valid operators for expr are listed below, in decreasing order of precedence.

As an example of the last operator, consider the following:

Tcl supports the following mathematical functions in expressions:

Because the construct,

occurs so often, the incr command was introduced.

The defualt is to increment by 1.

Control Structures

Tcl supports a wide range of control structures for program flow, including conditionals, loops and selections.

The if command evaluates expr1 and if it is true, executes body1, other wise it executes body2.

It's recommended practice to build the construct like this:

switch

The Tcl switch command is the direct analog of the UNIX shell case statement and the C switch.

Options coontrol the matching technique to be used. These may be:

for

The tcl for statement is very similar to the for statement in C.

A break command in the body of the loop causes it to terminate.

A continue command in the body of the loop causes it to start the next pass through the loop.

Each time the loop is completed, the next expression is evaluated.

while

The while command acts in a similar way to the while statement in C.

It repeatedly evaluates the test string and executes the Tcl command body until test yields a Boolean false value.

Error Handling

When the Tcl interpreter encounters an error, it usually prints a message and halts.

error

The error command generates an error and terminates execution unless the error is caught or trapped.

catch

The catch command evaluates the given script, trapping any errors that occur.

Here's an example taken from the Tcl program, concord, that we'll see later:

String Operations

Tcl is essentially a string-based language interpreter. It provides a rich set of commands for manipulating strings and string values.

string

The main string manipulation command is string.

The options to string are given below.

first, last, compare

first and last search for the appropriate occurrence of string1 in string2 and returns the index.

For example:

compare performs a character-by-character comparison in the same way as strcmp in C.

index

index returns a single character from string at index position num.

For example:

length

length returns the length of string.

For example:

match

match returns 1 if the string matches pattern, 0 otherwise.

For example:

range

range returns a substring of string from index position first to last.

For example:

tolower, toupper

These arguments return a string made from the charcters of string converted to the appropriate case.

For example:

trim, trimleft, trimright

These arguments return a substring of string, but with certain characters from the set char removed.

trim removes leading and trailing characters, while trimleft removes leading and trimright removes trailing characters.

For example:

wordstart, wordend

These return the index in string of the first character of/after the word containing the position index.

For example:

Glob Matching

In the string match and the switch -glob commands, a form of pattern matching is used.

For a string to match a pattern, they must be identical, except for special sequences that may appear in the pattern. These are:

regexp and regsub Matching

In the regexp and regsub commands and the -regexp option of the switch command, patterns are used to match strings.

The string must be identical to the expression, with the exception of special sequences that may occur in the pattern specifier. These are:

append

The append commands adds the value arguments to the end of the current value of the variable varname.

Given,

the following two Tcl fragments are equivalent, but the second can be more efficient.

regexp

The regexp command uses regular expressions to look for a match in string.

This example looks for a number starting with a 3:

Options that may be used to control the matching are:

regsub

The regsub command matches string against a given regular expression and writes a new string to the variable varname.

The new string is a copy of the subst argument with subsititutions carried out. These are as follows:

This example changes a leading 3 to a 5:

Try it Out - String Matching and Substitution

Here's an example of string matching and substitution:

How It Works

Several calls to regexp are shown matching dates to days in the weekend and extracting information from a date.

The variable parsedate is set to an expression that describes a value date. It uses several key forms:

Arrays

Arrays elements are special variables accessed with an index in parentheses following the array name.

Tcl supports a form of array known as an associative array.


Array indices are not limited to numberic values!

array

Arrays may be manipulated by the array command, which takes a number of options.

exists

This returns 1 if arrayname is an array, 0 otherwise.

get

This returns a list of pairs of elements containing array indices and associated values.

names

This returns a lists of array index names.

set

This sets the elements of the array arrayname.

size

This returns the size of an array.

Here are samples of the above array command options.

Lists

Tcl has full support for lists.

The syntax for Tcl lists is the brace group.

list

We can create lists using the list command.

We need to add braces and backslashes as necessary

split

The split command is used to create a list from a string.

If the delimiters list is empty, rather than omitted altogether, all characters in the string are individually included as list elements.

join

The join command is the opposite of split.

It creates a string by recursively joining together elements of a list.

concat

The concat command takes several arguments, treats them as lists and concatenates them.

It strips off one level of braces as it joins lists.

Arguments have leading and trailing spaces removed. Each list element is separated by a single space.

lappend

We can use the lappend command to add further elements to a list.

Each of the arguments to lappend is added as a list element to the existing list listvar.

lindex

We use the lindex command to retrieve an element at position index from a list.

We can use the keyword end in place of an index to refer to the last element in the list.

linsert

We can use the linsert command to insert elements into a list.

notice that the original list is not itself affected by the linsert command.

llength

We can obtain teh length of a list by the llength command.

An empty list returns a length of zero.

lrange

A consecutive subset of a list may be extracted by the lrange command.

The elements in positions first through last in the list list are extracted and a new list with just htose elements is returned.

lreplace

We can replace elements in a list by using the lreplace command.

The elements in positions first through last in the list list are replaced with the given arguments.

lsearch

We can use lsearch to search a list for elements that match a pattern.

The given list is searched for elements that match the specified pattern, and an index of the first matching element is returned.

lsort

We can use the lsort command to sort a list according to a number of criteria.

The default action is to order by ascending alphabetical.

The options to lsort that change the type of sort performed are:

foreach

We can use foreach to separately evaluate or use each element in a list.

Here's an example


In general, foreach command can take a list of variable names and a number of lists.

Procedures

Procedures in Tcl are similar to those of other languages.

We must define all procedures with the prod command before they can be called.

Arguments passed to the procedure when it is executed are substituted for the list of variables, args.

We can prematurely terminate procedures with the return command.

Try It Out - Procedures

Here's a simple procedure for calculating a factorial:.


How It Works

The procedure fact builds up the required factorial by iteration.

upvar

To gain access to a global variable, we must use the command upvar, which allows access to variables at a higher level in the call stack.

The most common case is simply to provide access to global variables with:

Below is an example of the proper usage of upvar:

Input and Output

Tcl provides a sophisticated system for input and output.

open

The open command establishes a connection to a file or a command pipe.

If present, the access argument determines how the file is to be opened.

close

The close command closes the channel given by channelID, which must have been obtained from a previous call to open.

read

The read command reads all of the input available on a channel identifier.

gets

The gets command reads a string form channel.

The string is placed into the optional variable, varname.

puts

The puts command writes output to a channel.

Here is a sample example of open, puts, gets, and close.

format

The format command is the Tcl equivalent of the C library function sprintf. The format command generates a formatted string.

scan

The scan command is the Tcl equivalent of the C librry function sscanf.

file

File manipulations are carried out in Tcl by the file command. it accepst a number of options for changing and inspecting file characteristics.

atime, mtime

This returns a string describing the last access time/modified time of the file file.

dirname

This returns the directory part of the file naem, i.e. all the characters before the last / character.

For example:

exists, executable

This returns 1 if the file exists/is executable, 0 otherwise.

for example:

extension, rootname

This returns the file extension / file root name.

For example:

isdirectory, isfile

Returns 1 if name refers to a directroy/regular file.

owned

This returns 1 if the file is owned by the current user.

readable, writeable

This returns 1 if the file is readable/writeable..

size

This returns the file size in bytes.

A Tcl Program

Here's a simple Tcl program that generates a histogram of the frequencies of word usage in a text file.

Try It Out - A Concordance Program

1. Type in the listing below, concord.tc1, starting with specifying the shell.


2. Remembering that argv is the program arguments array, parse the command line arguments. Set FileToRead and give help.

3. Set the default input source to the standard input. If a file has been specified, open it 'safety'.

4. Initialize the word and line counters, then read each line of input.

5. Output a summary, then all the words found, then each word accompanied by its count.

Let's try this program out on a text file, such as its own source code.

We get output like this (edited for brevity):


How It Works

This program prints out the list of words that it found before the frequency listing.

Network Support

Tcl has direct support for networking. The key command is socket.

Try It Out - socket

Here's a complete program, socket.c, in Tcl to display the time of day from a networked computer.


How It Works

Tcl has built-in support for UNIX networking.

Creating a New Tcl

The Tcl language should be embeddable, so that we can include scripts written in Tcl in other command line programs.

Tcl Extensions

Over the years, there have been a large number of extensions to Tcl.

expect

The expect program is a Tcl interpreter extended with additional functions aimed particularly at automatic control of interactive programs.

[incr Tcl]

This extension, the name of which is a pun on C++, adds object oriented features to Tcl.

TclX

TclX is 'extended Tcl'.

Networking

There are a number of extensions to Tcl that add networking support.

Graphics

MAny extensions have been developed to support graphics and additional operations. Tk under X Windows systems is the most widely used.

Tk

TK (for Tool Kit), is a major Tcl extension. It bestows on Tcl the ability to create and manipulate graphical user interface objects.


tgdb

tgdb is a front-end to the GNU debugger, gdb.

Summary

This chapter looked at the Tool Command Language, Tcl..


CS 248 - UNIX Programming Web Site Menu
Information | Syllabus | Schedule | Online "Lectures" | Projects | Quizzes | Web Board



Copyright © 2001 by James L. Fuller, all rights reserved.