Monday, November 17, 2008

More about Variables

The set command will return the value of a variable if it is only passed a single
argument. It treats that argument as a variable name and returns the current
value of the variable. The dollar-sign syntax used to get the value of a variable is
really just an easy way to use the set command. Example 1–15 shows a trick you
can play by putting the name of one variable into another variable:
* Ironically, Tcl 8.0 introduced a byte-code compiler, and the first releases of Tcl 8.0 had a bug in the compiler
that caused this loop to terminate! This bug is fixed in the 8.0.5 patch release.
14 Tcl Fundamentals Chap. 1

Example 1–15 Using set to return a variable value.
set var {the value of var}
=> the value of var
set name var
=> var
set name
=> var
set $name
=> the value of var
This is a somewhat tricky example. In the last command, $name gets substituted
with var. Then, the set command returns the value of var, which is the
value of var. Nested set commands provide another way to achieve a level of
indirection. The last set command above can be written as follows:
set [set name]
=> the value of var
Using a variable to store the name of another variable may seem overly
complex. However, there are some times when it is very useful. There is even a
special command, upvar, that makes this sort of trick easier. The upvar command
is described in detail in Chapter 7.
Funny Variable Names
The Tcl interpreter makes some assumptions about variable names that
make it easy to embed variable references into other strings. By default, it
assumes that variable names contain only letters, digits, and the underscore.
The construct $foo.o represents a concatenation of the value of foo and the literal
“.o”.
If the variable reference is not delimited by punctuation or white space,
then you can use curly braces to explicitly delimit the variable name (e.g., ${x}).
You can also use this to reference variables with funny characters in their name,
although you probably do not want variables named like that. If you find yourself
using funny variable names, or computing the names of variables, then you may
want to use the upvar command.

Example 1–16 Embedded variable references.
set foo filename
set object $foo.o
=> filename.o
set a AAA
set b abc${a}def
=> abcAAAdef
set .o yuk!
set x ${.o}y
=> yuk!y
More about Math Expressions 15
I. Tcl Basics
The unset Command
You can delete a variable with the unset command:
unset varName varName2 ...
Any number of variable names can be passed to the unset command. However,
unset will raise an error if a variable is not already defined.
Using info to Find Out about Variables
The existence of a variable can be tested with the info exists command.
For example, because incr requires that a variable exist, you might have to test
for the existence of the variable first.
Example 1–17 Using info to determine if a variable exists.
if {![info exists foobar]} {
set foobar 0
} else {
incr foobar
}
Example 7–6 on page 86 implements a new version of incr which handles this
case.
More about Math Expressions
This section describes a few fine points about math in Tcl scripts. In Tcl 7.6 and
earlier versions math is not that efficient because of conversions between strings
and numbers. The expr command must convert its arguments from strings to
numbers. It then does all its computations with double precision floating point
values. The result is formatted into a string that has, by default, 12 significant
digits. This number can be changed by setting the tcl_precision variable to the
number of significant digits desired. Seventeen digits of precision are enough to
ensure that no information is lost when converting back and forth between a
string and an IEEE double precision number:
Example 1–18 Controlling precision with tcl_precision.
expr 1 / 3
=> 0
expr 1 / 3.0
=> 0.333333333333
set tcl_precision 17
=> 17
expr 1 / 3.0
# The trailing 1 is the IEEE rounding digit
=> 0.33333333333333331
16 Tcl Fundamentals Chap. 1
In Tcl 8.0 and later versions, the overhead of conversions is eliminated in
most cases by the built-in compiler. Even so, Tcl was not designed to support
math-intensive applications. You may want to implement math-intensive code in
a compiled language and register the function as a Tcl command as described in
Chapter 44.
There is support for string comparisons by expr, so you can test string values
in if statements. You must use quotes so that expr knows to do string comparisons:
if {$answer == "yes"} { ... }
However, the string compare and string equal commands described in
Chapter 4 are more reliable because expr may do conversions on strings that
look like numbers. The issues with string operations and expr are discussed on
page 48.
Expressions can include variable and command substitutions and still be
grouped with curly braces. This is because an argument to expr is subject to two
rounds of substitution: one by the Tcl interpreter, and a second by expr itself.
Ordinarily this is not a problem because math values do not contain the characters
that are special to the Tcl interpreter. The second round of substitutions is
needed to support commands like while and if that use the expression evaluator
internally.
Grouping expressions can make them run more efficiently.
You should always group expressions in curly braces and let expr do command
and variable substitutions. Otherwise, your values may suffer extra conversions
from numbers to strings and back to numbers. Not only is this process
slow, but the conversions can loose precision in certain circumstances. For example,
suppose x is computed from a math function:
set x [expr {sqrt(2.0)}]
At this point the value of x is a double-precision floating point value, just as
you would expect. If you do this:
set two [expr $x * $x]
then you may or may not get 2.0 as the result! This is because Tcl will substitute
$x and expr will concatenate all its arguments into one string, and then parse
the expression again. In contrast, if you do this:
set two [expr {$x * $x}]
then expr will do the substitutions, and it will be careful to preserve the floating
point value of x. The expression will be more accurate and run more efficiently
because no string conversions will be done. The story behind Tcl values is
described in more detail in Chapter 44 on C programming and Tcl.
Comments
Tcl uses the pound character, #, for comments. Unlike in many other languages,
the # must occur at the beginning of a command. A # that occurs elsewhere is not
treated specially. An easy trick to append a comment to the end of a command is
Substitution and Grouping Summary 17
I. Tcl Basics
to precede the # with a semicolon to terminate the previous command:
# Here are some parameters
set rate 7.0 ;# The interest rate
set months 60 ;# The loan term
One subtle effect to watch for is that a backslash effectively continues a
comment line onto the next line of the script. In addition, a semicolon inside a
comment is not significant. Only a newline terminates comments:
# Here is the start of a Tcl comment \
and some more of it; still in the comment
The behavior of a backslash in comments is pretty obscure, but it can be
exploited as shown in Example 2–3 on page 27.
A surprising property of Tcl comments is that curly braces inside comments
are still counted for the purposes of finding matching brackets. I think the motivation
for this mis-feature was to keep the original Tcl parser simpler. However,
it means that the following will not work as expected to comment out an alternate
version of an if expression:
# if {boolean expression1} {
if {boolean expression2} {
some commands
}
The previous sequence results in an extra left curly brace, and probably a
complaint about a missing close brace at the end of your script! A technique I use
to comment out large chunks of code is to put the code inside an if block that
will never execute:
if {0} {
unused code here
}

A Factorial Example

To reinforce what we have learned so far, below is a longer example that uses a
while loop to compute the factorial function:

Example 1–13 A while loop to compute factorial.
proc Factorial {x} {
set i 1; set product 1
while {$i <= $x} {
set product [expr $product * $i]
incr i
}
return $product
}
Factorial 10
=> 3628800
The semicolon is used on the first line to remind you that it is a command
terminator just like the newline character. The while loop is used to multiply all
the numbers from one up to the value of x. The first argument to while is a boolean
expression, and its second argument is a command body to execute. The
while command and other control structures are described in Chapter 6.
The same math expression evaluator used by the expr command is used by
while to evaluate the boolean expression. There is no need to explicitly use the
expr command in the first argument to while, even if you have a much more
complex expression.
The loop body and the procedure body are grouped with curly braces in the
same way. The opening curly brace must be on the same line as proc and while.
If you like to put opening curly braces on the line after a while or if statement,
you must escape the newline with a backslash:
while {$i < $x} \
{
set product ...
}
Always group expressions and command bodies with curly braces.
More about Variables 13
I. Tcl Basics
Curly braces around the boolean expression are crucial because they delay
variable substitution until the while command implementation tests the expression.
The following example is an infinite loop:
set i 1; while $i<=10 {incr i}
The loop will run indefinitely.* The reason is that the Tcl interpreter will
substitute for $i before while is called, so while gets a constant expression 1<=10
that will always be true. You can avoid these kinds of errors by adopting a consistent
coding style that groups expressions with curly braces:
set i 1; while {$i<=10} {incr i}
The incr command is used to increment the value of the loop variable i.
This is a handy command that saves us from the longer command:
set i [expr $i + 1]
The incr command can take an additional argument, a positive or negative
integer by which to change the value of the variable. Using this form, it is possible
to eliminate the loop variable i and just modify the parameter x. The loop
body can be written like this:
while {$x > 1} {
set product [expr $product * $x]
incr x -1
}
Example 1–14 shows factorial again, this time using a recursive definition.
A recursive function is one that calls itself to complete its work. Each recursive
call decrements x by one, and when x is one, then the recursion stops.
Example 1–14 A recursive definition of factorial.
proc Factorial {x} {
if {$x <= 1} {
return 1
} else {
return [expr $x * [Factorial [expr $x - 1]]]
}
}

Procedures

Tcl uses the proc command to define procedures. Once defined, a Tcl procedure
is used just like any of the other built-in Tcl commands. The basic syntax to
define a procedure is:
proc name arglist body
The first argument is the name of the procedure being defined. The second
argument is a list of parameters to the procedure. The third argument is a command
body that is one or more Tcl commands.
The procedure name is case sensitive, and in fact it can contain any characters.
Procedure names and variable names do not conflict with each other. As a
convention, this book begins procedure names with uppercase letters and it
begins variable names with lowercase letters. Good programming style is important
as your Tcl scripts get larger. Tcl coding style is discussed in Chapter 12.
Example 1–12 Defining a procedure.
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c
}
puts "The diagonal of a 3, 4 right triangle is [Diag 3 4]"
=> The diagonal of a 3, 4 right triangle is 5.0
The Diag procedure defined in the example computes the length of the diagonal
side of a right triangle given the lengths of the other two sides. The sqrt
function is one of many math functions supported by the expr command. The
variable c is local to the procedure; it is defined only during execution of Diag.
Variable scope is discussed further in Chapter 7. It is not really necessary to use
the variable c in this example. The procedure can also be written as:
proc Diag {a b} {
return [expr sqrt($a * $a + $b * $b)]
}
The return command is used to return the result of the procedure. The
return command is optional in this example because the Tcl interpreter returns
the value of the last command in the body as the value of the procedure. So, the
procedure could be reduced to:
proc Diag {a b} {
expr sqrt($a * $a + $b * $b)
}
Note the stylized use of curly braces in the example. The curly brace at the
end of the first line starts the third argument to proc, which is the command
body. In this case, the Tcl interpreter sees the opening left brace, causing it to
ignore newline characters and scan the text until a matching right brace is
found. Double quotes have the same property. They group characters, including
newlines, until another double quote is found. The result of the grouping is that
12 Tcl Fundamentals Chap. 1
the third argument to proc is a sequence of commands. When they are evaluated
later, the embedded newlines will terminate each command.
The other crucial effect of the curly braces around the procedure body is to
delay any substitutions in the body until the time the procedure is called. For
example, the variables a, b, and c are not defined until the procedure is called, so
we do not want to do variable substitution at the time Diag is defined.
The proc command supports additional features such as having variable
numbers of arguments and default values for arguments. These are described in

Grouping with Braces and Double Quotes

Double quotes and curly braces are used to group words together into one argument.
The difference between double quotes and curly braces is that quotes allow
substitutions to occur in the group, while curly braces prevent substitutions.
This rule applies to command, variable, and backslash substitutions.

Example 1–10 Grouping with double quotes vs. braces.
set s Hello
=> Hello
puts stdout "The length of $s is [string length $s]."
=> The length of Hello is 5.
puts stdout {The length of $s is [string length $s].}
=> The length of $s is [string length $s].
In the second command of Example 1–10, the Tcl interpreter does variable
and command substitution on the second argument to puts. In the third command,
substitutions are prevented, so the string is printed as is.
In practice, grouping with curly braces is used when substitutions on the
argument must be delayed until a later time (or never done at all). Examples
include loops, conditional statements, and procedure declarations. Double quotes
are useful in simple cases like the puts command previously shown.
Another common use of quotes is with the format command. This is similar
to the C printf function. The first argument to format is a format specifier that
often includes special characters like newlines, tabs, and spaces. The easiest way
to specify these characters is with backslash sequences (e.g., \n for newline and
\t for tab). The backslashes must be substituted before the format command is
Grouping with Braces and Double Quotes 9
I. Tcl Basics
called, so you need to use quotes to group the format specifier.
puts [format "Item: %s\t%5.3f" $name $value]
Here format is used to align a name and a value with a tab. The %s and
%5.3f indicate how the remaining arguments to format are to be formatted. Note
that the trailing \n usually found in a C printf call is not needed because puts
provides one for us. For more information about the format command, see page

Square Brackets Do Not Group
The square bracket syntax used for command substitution does not provide
grouping. Instead, a nested command is considered part of the current group. In
the command below, the double quotes group the last argument, and the nested
command is just part of that group.
puts stdout "The length of $s is [string length $s]."
If an argument is made up of only a nested command, you do not need to
group it with double-quotes because the Tcl parser treats the whole nested command
as part of the group.
puts stdout [string length $s]
The following is a redundant use of double quotes:
puts stdout "[expr $x + $y]"
Grouping before Substitution
The Tcl parser makes a single pass through a command as it makes grouping
decisions and performs string substitutions. Grouping decisions are made
before substitutions are performed, which is an important property of Tcl. This
means that the values being substituted do not affect grouping because the
grouping decisions have already been made.
The following example demonstrates how nested command substitution
affects grouping. A nested command is treated as an unbroken sequence of characters,
regardless of its internal structure. It is included with the surrounding
group of characters when collecting arguments for the main command.

Example 1–11 Embedded command and variable substitution.
set x 7; set y 9
puts stdout $x+$y=[expr $x + $y]
=> 7+9=16
In Example 1–11, the second argument to puts is:
$x+$y=[expr $x + $y]
The white space inside the nested command is ignored for the purposes of
grouping the argument. By the time Tcl encounters the left bracket, it has
already done some variable substitutions to obtain:
10 Tcl Fundamentals Chap. 1
7+9=
When the left bracket is encountered, the interpreter calls itself recursively
to evaluate the nested command. Again, the $x and $y are substituted before
calling expr. Finally, the result of expr is substituted for everything from the left
bracket to the right bracket. The puts command gets the following as its second
argument:
7+9=16

Grouping before substitution.
The point of this example is that the grouping decision about puts’s second
argument is made before the command substitution is done. Even if the result of
the nested command contained spaces or other special characters, they would be
ignored for the purposes of grouping the arguments to the outer command.
Grouping and variable substitution interact the same as grouping and command
substitution. Spaces or special characters in variable values do not affect grouping
decisions because these decisions are made before the variable values are
substituted.
If you want the output to look nicer in the example, with spaces around the
+ and =, then you must use double quotes to explicitly group the argument to
puts:
puts stdout "$x + $y = [expr $x + $y]"
The double quotes are used for grouping in this case to allow the variable and
command substitution on the argument to puts.
Grouping Math Expressions with Braces
It turns out that expr does its own substitutions inside curly braces. This is
explained in more detail on page 15. This means you can write commands like
the one below and the substitutions on the variables in the expression still occur:
puts stdout "$x + $y = [expr {$x + $y}]"
More Substitution Examples
If you have several substitutions with no white space between them, you
can avoid grouping with quotes. The following command sets concat to the value
of variables a, b, and c all concatenated together:
set concat $a$b$c
Again, if you want to add spaces, you’ll need to use quotes:
set concat "$a $b $c"
In general, you can place a bracketed command or variable reference anywhere.
The following computes a command name:
[findCommand $x] arg arg
When you use Tk, you often use widget names as command names:
$text insert end "Hello, World!"
Procedures 11

Tcl Basics

The implementation of expr is careful to preserve accurate numeric values
and avoid conversions between numbers and strings. However, you can make
expr operate more efficiently by grouping the entire expression in curly braces.
The explanation has to do with the byte code compiler that Tcl uses internally,
and its effects are explained in more detail on page 15. For now, you should be
aware that these expressions are all valid and run a bit faster than the examples
shown above:
Example 1–7 Grouping expressions with braces.
expr {7.2 / 4}
set len [expr {[string length foobar] + $x}]
set pi [expr {2*asin(1.0)}]
Backslash Substitution
The final type of substitution done by the Tcl interpreter is backslash substitution.
This is used to quote characters that have special meaning to the interpreter.
For example, you can specify a literal dollar sign, brace, or bracket by
quoting it with a backslash. As a rule, however, if you find yourself using lots of
backslashes, there is probably a simpler way to achieve the effect you are striving
for. In particular, the list command described on page 61 will do quoting for
you automatically. In Example 1–8 backslash is used to get a literal $:
Example 1–8 Quoting special characters with backslash.
set dollar \$foo
=> $foo
set x $dollar
=> $foo
Only a single round of interpretation is done.
The second set command in the example illustrates an important property
of Tcl. The value of dollar does not affect the substitution performed in the
assignment to x. In other words, the Tcl parser does not care about the value of a
variable when it does the substitution. In the example, the value of x and dollar
is the string $foo. In general, you do not have to worry about the value of variables
until you use eval, which is described in Chapter 10.
You can also use backslash sequences to specify characters with their Unicode,
hexadecimal, or octal value:
set escape \u001b
set escape \0x1b
set escape \033
The value of variable escape is the ASCII ESC character, which has character
code 27. The table on page 20 summarizes backslash substitutions.
8 Tcl Fundamentals Chap. 1
A common use of backslashes is to continue long commands on multiple
lines. This is necessary because a newline terminates a command. The backslash
in the next example is required; otherwise the expr command gets terminated by
the newline after the plus sign.
Example 1–9 Continuing long lines with backslashes.
set totalLength [expr [string length $one] + \
[string length $two]]
There are two fine points to escaping newlines. First, if you are grouping an
argument as described in the next section, then you do not need to escape newlines;
the newlines are automatically part of the group and do not terminate the
command. Second, a backslash as the last character in a line is converted into a
space, and all the white space at the beginning of the next line is replaced by this
substitution. In other words, the backslash-newline sequence also consumes all
the leading white space on the next line.

Math Expressions

The Tcl interpreter itself does not evaluate math expressions. Tcl just does
grouping, substitutions and command invocations. The expr command is used to
parse and evaluate math expressions.
Example 1–4 Simple arithmetic.
expr 7.2 / 4
=> 1.8
The math syntax supported by expr is the same as the C expression syntax.
The expr command deals with integer, floating point, and boolean values. Logical
operations return either 0 (false) or 1 (true). Integer values are promoted to floating
point values as needed. Octal values are indicated by a leading zero (e.g., 033
is 27 decimal). Hexadecimal values are indicated by a leading 0x. Scientific notation
for floating point numbers is supported. A summary of the operator precedence
is given on page 20.
You can include variable references and nested commands in math expressions.
The following example uses expr to add the value of x to the length of the
string foobar. As a result of the innermost command substitution, the expr command
sees 6 + 7, and len gets the value 13:
Example 1–5 Nested commands.
set x 7
set len [expr [string length foobar] + $x]
=> 13
The expression evaluator supports a number of built-in math functions.
(For a complete listing, see page 21.) Example 1–6 computes the value of pi:
Example 1–6 Built-in math functions.
set pi [expr 2*asin(1.0)]
=> 3.1415926535897931
Backslash Substitution 7

Command Substitution

The second form of substitution is command substitution. A nested command is
delimited by square brackets, [ ]. The Tcl interpreter takes everything between
the brackets and evaluates it as a command. It rewrites the outer command by
replacing the square brackets and everything between them with the result of
the nested command. This is similar to the use of backquotes in other shells,
except that it has the additional advantage of supporting arbitrary nesting of
commands.

Example 1–3 Command substitution.
set len [string length foobar]
=> 6
In Example 1–3, the nested command is:
string length foobar
This command returns the length of the string foobar. The string command
is described in detail starting on page 45. The nested command runs first.
6 Tcl Fundamentals Chap. 1
Then, command substitution causes the outer command to be rewritten as if it
were:
set len 6
If there are several cases of command substitution within a single command,
the interpreter processes them from left to right. As each right bracket is
encountered, the command it delimits is evaluated. This results in a sensible
ordering in which nested commands are evaluated first so that their result can
be used in arguments to the outer command.

Variables

The set command is used to assign a value to a variable. It takes two arguments:
The first is the name of the variable, and the second is the value. Variable names
can be any length, and case is significant. In fact, you can use any character in a
variable name.
It is not necessary to declare Tcl variables before you use them.
The interpreter will create the variable when it is first assigned a value.
The value of a variable is obtained later with the dollar-sign syntax, illustrated
in Example 1–2:

Example 1–2 Tcl variables.
set var 5
=> 5
set b $var
=> 5
The second set command assigns to variable b the value of variable var.
The use of the dollar sign is our first example of substitution. You can imagine
that the second set command gets rewritten by substituting the value of var for
$var to obtain a new command.
set b 5
The actual implementation of substitution is more efficient, which is important
when the value is large.

Tcl Commands

Tcl stands for Tool Command Language. A command does something for you, like
output a string, compute a math expression, or display a widget on the screen.
Tcl casts everything into the mold of a command, even programming constructs
ike variable assignment and procedure definition. Tcl adds a tiny amount of
syntax needed to properly invoke commands, and then it leaves all the hard work
up to the command implementation.

The basic syntax for a Tcl command is:
command arg1 arg2 arg3 ...

The command is either the name of a built-in command or a Tcl procedure.
White space (i.e., spaces or tabs) is used to separate the command name and its
arguments, and a newline (i.e., the end of line character) or semicolon is used to
terminate a command. Tcl does not interpret the arguments to the commands
except to perform grouping, which allows multiple words in one argument, and
substitution, which is used with programming variables and nested command
calls. The behavior of the Tcl command processor can be summarized in three
basic steps:
• Argument grouping.
• Value substitution of nested commands, variables, and backslash escapes.
• Command invocation. It is up to the command to interpret its arguments.
This model is described in detail in this Chapter.
Hello, World!

Example 1–1 The “Hello, World!” example.
puts stdout {Hello, World!}
=> Hello, World!
In this example, the command is puts, which takes two arguments: an I/O
stream identifier and a string. puts writes the string to the I/O stream along
with a trailing newline character. There are two points to emphasize:
• Arguments are interpreted by the command. In the example, stdout is used
to identify the standard output stream. The use of stdout as a name is a
convention employed by puts and the other I/O commands. Also, stderr is
used to identify the standard error output, and stdin is used to identify the
standard input. Chapter 9 describes how to open other files for I/O.
• Curly braces are used to group words together into a single argument. The
puts command receives Hello, World! as its second argument.
The braces are not part of the value.
The braces are syntax for the interpreter, and they get stripped off before
the value is passed to the command. Braces group all characters, including newlines
and nested braces, until a matching brace is found. Tcl also uses double
quotes for grouping. Grouping arguments will be described in more detail later.
Variables 5

Tcl Fundamentals

Tcl is a string-based command language.
The language has only a few fundamental constructs and relatively little
syntax, which makes it easy to learn. The Tcl syntax is meant to be simple. Tcl is
designed to be a glue that assembles software building blocks into applications.
A simpler glue makes the job easier. In addition, Tcl is interpreted when the
application runs. The interpreter makes it easy to build and refine your application
in an interactive manner. A great way to learn Tcl is to try out commands
interactively. If you are not sure how to run Tcl on your system, see Chapter 2 for
instructions for starting Tcl on UNIX, Windows, and Macintosh systems.
This chapter takes you through the basics of the Tcl language syntax. Even
if you are an expert programmer, it is worth taking the time to read these few
pages to make sure you understand the fundamentals of Tcl. The basic mechanisms
are all related to strings and string substitutions, so it is fairly easy to
visualize what is going on in the interpreter. The model is a little different from
some other programming languages with which you may already be familiar, so
it is worth making sure you understand the basic concepts.

Tuesday, August 12, 2008

Introduction to the Tcl Programming Language

© Moreniche


cl (pronounced Tickle) is a

general purpose programming

language originally intended

to be embedded in other

applications as a configuration

and extension language. The success

of one of its most important

embeddings, the Tk toolkit for

the X Windows System, has resulted

in Tcl and Tk together being

most heavily used for building

graphical user interfaces

(GUIs). It is also heavily used as

a scripting language like Awk,

Perl or Rexx, and (as Expect)

is used to script interactive

applications (e.g. , to automate

telnet logins to various information

vendors).

Tcl is virtually unique in the combination

of features it offers:

Scripting Language

Tcl is a powerful scripting language

that runs under Unix,

Linux, VMS, DOS / Windows,

OS/2, and MacOS (at least). It

provides all the usual high-level

programming features that we've

come to expect from languages

like the Unix shell, Awk, Perl, or

Rexx, such as :

· Variable-length strings

· Associative arrays

· Lists

· Keyed lists (aka structs,

structures or records)

· Pattern matching with regular

expressions

· Ability to define or redefine

procedures at run-time

· Full file access

· Error handling

Embeddability

Tcl is a small language designed

to be embedded in other applications

(C programs for example)

as a configuration and extension

language. This minimizes the

number of languages that users

need to learn in order to configure

their applications, and makes

these applications programmable

with no extra effort. In addition,

Tcl is a complete and welldesigned

programming language,

whereas many existing configuration

languages were designed

(to be kind) in an ad hoc manner.

Extensibility

Tcl is specially designed to make

it extremely easy to extend the

language by the addition of new

primitives in C. These new

primitives are truly first-class

citizens of the language, sharing

the same error handling and

memory management as the

original primitives. This has led

to many useful extensions, such

as DBMS access (extensions exist

for Oracle, Sybase, Ingres, Postgres

and many other DBMS's),

SNMP, Motif, etc. In addition,

this allows Tcl programs to be

optimized by moving timecritical

code into C.

Equivalence of Data and

Programs

Like Lisp, Tcl uses the same

representation for data and for

programs. This means that Tcl

programs or scripts can be manipulated

as data: stored in variables,

written to and later read

from files or databases, passed

from one Tcl program to another

across the Internet, etc. In addition,

it means that the programmer

can create new Tcl control

structures or error handling routines

as easily as writing a simple

function.

Automatic Memory

Management

All Tcl data structures are dynamically

allocated and fully

variable in size. The programmer

never needs to allocate memory

or specify maximum sizes.

Event-Driven

Programming

Tcl supports event-driven programming

(required for GUI programming)

with the ability to associate

Tcl code with any variable

or array element (the code is executed

automatically whenever the

variable is read or written).

IPC Between Multiple Tcl

Applications

Tcl supports the passing of Tcl

code as messages between Tcl

applications running on different

machines across the Internet.

This allows client-server

protocols which incorporate

the full power of the Tcl language,

and makes it possible to

write very tightly-integrated

applications.

Program Development

Tools

Tcl has a powerful symbolic debugger,

timing and profiling

tools, language sensitive editing

modes for Emacs, a WYSIWYG

GUI builder (xf), a real-time application

monitor (tkinspect), etc.

Freely Redistributable

The source code for the Tcl language

system is freely copyable

for any purpose, so it can be

used in commercial applications

as well as academic applications

and freeware.

Builds stand-alone TCL/TK executables. No compiler required!

OR Use it as a single-file WISH shell

The freewrap program turns

TCL/TK scripts into single-file

binary executable programs.

The resulting program can be distributed

to machines that do not

have TCL/TK installed. The executable

will also work on machines

that have TCL/TK installed

but will use its own TCL / TK

"image". freeWrap itself does not

need TCL / TK installed to run.

The freeWrap program is a TCL/

TK script that has been attached

to a single-file version of the WISH

shell program. The single-file

WISH was created with the help of

the ZIP Virtual File System (ZVFS)

source code provided by D. Richard

Hipp. The ZVFS code has been

adapted for use with TCL's virtual

file system interface.

Easy, one-step wrapping.

FreeWrap consists of a single executable

file. There is no setup required.

Wrapping is accomplished

with a single command.

freewrapTCLSH can be used

to wrap TCL-only scripts.

FreewrapTCLSH creates a single

executable file from a TCL script.

The wrapping syntax is identical to

the freewrap program. This produces

a console-only type of program.

freeWrap can be used as a

single file stand-alone WISH

Renaming the freewrap program

to some other file name causes

freewrap to behave as a standalone,

single-file WISH that can

be used to run any TCL/TK script.

freewrapTCLSH can be used

as a single file stand - alone

TCLSH shell

Renaming the freewrapTCLSH

program to some other file name

causes freewrapTCLSH to behave

as a a stand-alone, single-file

TCLSH shell that can be used to

run any TCL script.

Shared libraries can be used

with your wrapped programs.

FreeWrapped applications can

load TCL/TK shared library extensions

that have been compiled

with the STUBS interface.

Your wrapped programs can

be customized with your own

window icons.

The Windows version of freeWrap

can incorporate your own customized

icon into your wrapped application.

No license fees for

wrapped programs.

There are no license fees associated

with freeWrap. See the free-

Wrap documentation [ 1 ]

Cross-platform generation

of programs is supported.

The -w "wrap using" option allows

cross-platform creation of wrapped

applications without the use of the

target computer system.

freeWrap includes several

Windows-specific commands

for installing your wrapped

applications.

These commands can be used to

determine the location of Windows'

special directories and make for

easy creation of file extension

associations and shortcuts.

freeWrap includes commands

for ZIP file creation and

extraction.

Due to freeWrap's use of the ZIP

Virtual File System any ZIP

archive can be opened so its

contents look like a simple file

subdirectory. The archive's files

are automatically decompressed

when read with TCL commands.

The makeZIP command allows

creation and modification of ZIP

archives from within your free-

Wrapped application.

Availability

FreeWrap executables are freely

available for both Linux and

Windows 95 / 98 / NT / 2000 / XP.

Instructions and source code for

building freeWrap on both Windows

and UNIX platforms are

included in the freeWrap source

code distribution. See the Downloads

table below for specifics [ 2 ]

Versions of freeWrap that include

the BLT and TkTable extensions

to TCL/TK are also available for

download. TCL-only versions of

freeWrap are available also for

wrapping TCL (non-TK) scripts.

Tcl is a string-based command language. The language has only a few fundamental constructs and

relatively little syntax, which makes it easy to learn. The Tcl syntax is meant to be simple. Tcl is designed

to be a glue that assembles software building blocks into applications. A simpler glue makes the job easier.

In addition, Tcl is interpreted when the application runs. The interpreter makes it easy to build and refine

your application in an interactive manner. A great way to learn Tcl is to try out commands interactively.

«TclTutor is a Computer Aided Instruction package that teaches the basics of the Tcl

programming language. The 40+ lessons in this package can be completed in under 10

minutes each. You'll be ready to start simple programs after the first half dozen lessons.

This program will teach you the syntax for the main Tcl commands and options.» Available

for Mac OS8-10, Unix and Win95+. To download for Windows, pick «Self-Installing Zip» or

(preferably) « Free-Wrapped Executable. »

The Tcl Syntax

by Brent B. Welch An Introduction to Tcl Syntax

September, 1999

For a scripting language, Tcl has a simple syntax.

cmd arg arg arg

A Tcl command is formed by words separated

by white space. The first word is the name of the

command, and the remaining words are arguments

to the command.

$foo

The dollar sign ($) substitutes the value of a variable.

In this example, the variable name is foo.

[clock seconds]

Square brackets execute a nested command. For

example: if you want to pass the result of one command

as the argument to another, you use this syntax.

In this example, the nested command is clock

seconds, which gives the current time in seconds.

"some stuff"

Double quotation marks group words as a single argument

to a command. Dollar signs and square brackets

are interpreted inside double quotation marks.

{some stuff}

Curly braces also group words into a single argument.

In this case, however, elements within

the braces are not interpreted.

\

The backslash ( \ ) is used to quote special characters.

For example: \n generates a newline.

The backslash also is used to "turn off" the

special meanings of the dollar sign, quotation

marks, square brackets, and curly braces.

A Little Example

Below is a Tcl command that prints the current

time. It uses three Tcl commands: set, clock, and

puts. The set command assigns the variable. The

clock command manipulates time values. The puts

command prints the values.

set seconds [clock seconds]

puts "The time is [clock format $seconds]"

Note that you do not use $ when assigning a variable.

Only when you want the value do you use $. The

seconds variable isn't needed in the previous example.

You could print the current time with one command:

puts "The time is [clock format [clock

seconds]]"

Grouping and Substitution

The Tcl syntax is used to guide the Tcl parser

through three steps: argument grouping, result substitution,

and command dispatch.

1. Argument grouping. Tcl needs to determine

how to organize the arguments to the commands.

In the simplest case, white space separates arguments.

The quotation marks and braces syntax is used

to group multiple words into one argument. In the

previous example, double quotation marks are used

to group a single argument to the puts command.

2. Result substitution. After the arguments are

grouped, Tcl performs string substitutions. Put

simply: it replaces $foo with the value of the variable

foo, and it replaces bracketed commands with

their result. That substitutions are done after grouping

is crucial. This sequence ensures that unusual

values do not complicate the structure of commands.

3. Command dispatch. After substitution, Tcl

uses the command name as a key into a dispatch

table. It calls the C procedure identified in the table,

and the C procedure implements the command.

You also can write command procedures in Tcl.

There are simple conventions about argument passing

and handling errors.

Another Example

set i 0

while {$i <>

puts "$i squared = [expr $i*$i]"

incr i

}

Here, curly braces are used to group arguments

without doing any substitutions. The Tcl parser

knows nothing special about the while command.

It treats it like any other command. It is the

implementation of the while command knows that

the first argument is an expression, and the second

argument is more Tcl commands. The braces group

two arguments: the boolean expression that controls

the loop; and the commands in the loop body.

We also see two math expressions: the boolean

comparison and multiplication. The while command

automatically evaluates its first argument as an

expression. In other cases you must explicitly use

the expr command to perform math evaluation.

TCL_Notes page 5 of 6

Command Dispatch

Lastly, Tcl calls something else to do the hard work.

We've seen that Tcl uses expr to perform math

functions; puts to handle output functions; and set

to assign variables. These Tcl commands are implemented

by a C procedure that has registered itself

with Tcl. The C command procedures take the string

arguments from the Tcl command and return a new

string as their result. It is very easy to write C command

procedures. They can do everything from

accessing databases to creating graphical user

interfaces. Tcl, the language, doesn't really know

what the commands do. It just groups arguments,

substitutes results, and dispatches the commands.

One Last Example

Here is the factorial procedure:

proc fac {x} {

if {$x <>

error "Invalid argument $x: must be a positive integer"

} elseif {$x <= 1} {

return 1

} else {

return [expr $x * [fac [expr $x-1]]]

}

}

More Reading

Chapter 1 of Practical Programming in Tcl and Tk

http://www.beedub.com/book/2nd/tclintro.doc.html

E. J. Friedman's Tcl/Tk Course:

http://www.linbox.com/ucome.rvt/any/doc_distrib/tcltk-8.3.2/TclCourse/TclWeek1.html

http://www.linbox.com/ucome.rvt/any/doc_distrib/tcltk-8.3.2/TclCourse/TclWeek2.html

http://www.linbox.com/ucome.rvt/any/doc_distrib/tcltk-8.3.2/TclCourse/TclWeek3.html

http://www.linbox.com/ucome.rvt/any/doc_distrib/tcltk-8.3.2/TclCourse/TclWeek4.html

http://www.linbox.com/ucome.rvt/any/doc_distrib/tcltk-8.3.2/TclCourse/TclWeek5.html

Brent B. Welch is the author of "Practical Programming in Tcl and Tk." Welch received a BS in

Aerospace Engineering at the University of Colorado, Boulder, in 1982 and an MS in Computer Science

at the University of California, Berkeley, in 1986 and a PhD in Computer Science at the University of

California, Berkeley, in 1990. Previously Welch was a member of research staff at Xerox PARC working

on distributed systems, and later a member of the Tcl/Tk team at Sun Microsystems Laboratories.

He is a member of the ACM and the IEEE Computer Society. Home Page: http://www.beedub.com/

TCL_Notes page 6 of 6

http://www.infoworld.com/cgi-bin/displayNew.pl?/petrel/980928np.htm

September 28, 1998

[ excerpts ]

The salacious truth of the scripting paradigm shift to Tcl/Tk and Python

ere's a buzz phrase that should become

big in the next year or so -- "scripting

language." Though you can build full-blown

applications with many scripting languages, they

are generally used to automate a complex series

of tasks you would normally have to type out at a

command prompt. Perl, sh, ksh, csh, bash,

Tcl / Tk, Rexx, Scheme, and Python are all

considered scripting languages.

The Web has raised the visibility of Perl in recent

years. Perl has become practically synonymous with

CGI, due to its elegant character - string handling.

Look for other scripting languages to get a boost

soon, as PCs get more robust and invade the

enterprise infrastructure where the advanced

workstations and minicomputers once ruled.

Why? -- As much as some people would like to

think PCs can replace big machines without

having to resort to a command-line paradigm,

I'm here to tell you it just ain't possible. GUIs

are by nature general purpose interfaces. They're

great for introducing simplicity and consistency

to applications that perform a predictable set of

individual tasks. But they're really lousy at handling

huge, complicated, and unpredictable administrative

operations that step outside the nice, neat

boundaries of predefined groups of users or files.

Imagine that you must grant specific limited

access to 30 directories, 253 files, five printers,

and 17 discussion groups for the Argyle Sock

Division of the worldwide sales force, but give

less-limited rights to any member of that subset

who is also on the management task force but

not based in France. Now imagine this task

requires administrative changes across multiple

applications and OS platforms. A generic GUI

administration tool just isn't going to cut it.

You're much better off writing a simple script.

That's not to say you can't give the script a GUI

front end, even if it is nothing more than a button

labeled "Go." But the administrative task itself

is nevertheless script material.

So expect scripting in general to take off soon. Of

the scripting languages available, I predict Tcl/Tk

and Python will eventually gain the popularity

Perl now enjoys. Although it's somewhat of an

apples and oranges comparison, both Tcl/Tk and

Python are easier to learn than Perl. And like

Perl, there is a version of Tcl/Tk and Python for

practically every platform, including Windows 95

and Windows NT.

Both Python and Tcl/Tk are actually combination

packages. Tcl consists of the Tool Command Language,

which provides most of its scripting capabilities;

and Tk, or TookKit, which adds the GUI

features to Tcl. Likewise, when people talk about

Python, they're usually referring to a combination

of Python, Tkinter, and Tk. Python is the objectoriented

scripting language. Tkinter is the wrapper

that allows Python to use Tk as its de facto standard

for GUI features.

Most important, Tcl/Tk and Python are easily

extensible. They hook into C, C++, and other

function libraries and programs quite easily.

Enterprising programmers have tapped this capability

to give Tcl/Tk and Python access to everything

from IMAP4 e-mail features to Informix,

Oracle, and Sybase database access. You can even

get an ODBC interface for Tcl/Tk on Windows.

Last but not least, the best selling point of Tcl/Tk

and Python is that they are free for download.

Are you using PCs more and enjoying it less?

Have you begun to discover the wonderful world

of scripting as a result?