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?