TechiWarehouse.Com


Top 3 Products & Services

1.
2.
3.

Dated: Aug. 12, 2004

Related Categories

Tcl/Tk Programming

Introduction

TCL/TK is a programming system developed by John Ousterhout at the University of California, Berkeley, which is easy to use, and which has very useful graphical interface facilities. TCL is the basic programming language, while TK is a ToolKit of widgets, which are graphical objects similar to those of other GUI toolkits, such as Xlib, Xview and Motif. Unlike many of the other toolkits, it is not necessary to use C or C++ in order to manipulate the widgets, and useful applications can be built very rapidly once some expertise of the TCL/TK system has been gained.

Tcl is a software package which provides an extensible command-line interface and scripting language. Tcl is an acronym for Tool Command Language. Tk is a software package for building graphical user interfaces (GUIs). Tk is implemented as an extension to Tcl.

The TCL language is normally interpreted, so TCL applications will normally not run as fast as equivalent C programs. For a large class of applications this is not a disadvantage, however, since the speed of processing of modern computer systems is more than adequate. Where speed of processing is essential, use can be made of a TCL compiler, or processing can be carried out in a compiled language, such as C or C++, and the user interface written in TCL.


History

Tcl/Tk TutorialTcl was originally intended to be a reusable command language. Its developers had been creating a number of interactive tools, each requiring its own command language. Since they were more interested in the tools themselves than the command languages they would employ, these command languages were constructed quickly, without regard to proper design.

After implementing several such "quick-and-dirty" command languages and experiencing problems with each one, they decided to concentrate on implementing a general-purpose, robust command language that could easily be integrated into new applications. Thus Tcl (Tool Command Language) was born.

Since that time, Tcl has been widely used as a scripting language. In most cases, Tcl is used in combination with the Tk ("Tool Kit") library, a set of commands and procedures that make it relatively easy to program graphical user interfaces in Tcl.

 

Tcl/Tk and C Language

The main difference between Tcl and languages such as C, is that Tcl is an interpreted rather than a compiled language. Tcl programs are simply scripts consisting of Tcl commands that are processed by a Tcl interpreter at run time. One advantage that this offers is that Tcl programs can themselves generate Tcl scripts that can be evaluated at a later time. This can be useful, for example, when creating a graphical user interface with a command button that needs to perform different actions at different times

Tcl is not meant to be a replacement language for C or Ada or any of the other high level languages. It is meant as a generic scripting language that could be embedded inside other languages to come up with a common interface. Tcl lacks things like arrays (but it does have associative arrays), and linked lists, but it was never meant to do those things. That is left to the language it's embedded into. There are however extensions to Tcl that drastically increase it's scope. Python is a object oriented version of Tcl.

 

An Introduction to Tcl Syntax 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 to 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. As stated earlier, 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.

Here is another example:

set i 0
while {$i < 10} {
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.

Command Dispatch
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 commands.

Example Here is the factorial procedure:

proc fac {x} {
if {$x < 0} {
error "Invalid argument $x: must be a positive integer"
} elseif {$x <= 1} {
return 1
} else {
return [expr $x * [fac [expr $x-1]]]
}
}

.

Basics of Tcl/Tk

Basics of Tk If you would like to type along with this portion of the basic tutorials, you should stop your tclsh (with control D), and use the Tk interpretive shell. Type 'blt_wish' to start a Tk interactive shell going and you will be presented with a '%' prompt, and a small window should appear on your screen. This shell is just like the tclsh, but it has graphics capabilities.

Using Tk, you use Tcl scripts just like before, but now you have more fun commands to play with. Tk uses X to implement a ready-made set of controls with a motif like look and feel. These are called widgets. Each widget is a member of a class in a hierarchy of other widgets. Each widget can contain any number of children widgets. Each widget has a name, which represents the widget, as well as where it is in the widget tree.

.a.b.c
This name refers to the widget 'c' which is a child of b, which in turn is a child of a, which is a child of the main widget (.). Some of the different widget types are: labels, buttons, checkbuttons, radiobuttons, canvases, messages, listboxes, scrollbars, scales, entries, frames, menus and menubuttons.

To create a widget you call the widget class you want, give it a name, and whatever configuration options you desire label .lab -text "Hello World" You will not actually see the widget until you use Tk's geometry manager to place it somewhere. There are a few kinds of geometry management in Tk, but they are too complex to go into great detail here. For now, to make your widget appear on the screen, you must pack it. pack .lab

 

How can I combine Tcl and C ?

Tcl was intended to be used along with C code. Because of this, there are several ways to combine the two. Here is a list of some of them (with man page references for further info):

Adding Commands to Tcl (Tcl_CreateCommand)
Command Traces (Tcl_CreateTrace)
Variable Traces (Tcl_TraceVar)
Getting/Setting Variables (Tcl_GetVar/Tcl_SetVar)
Linking Variables (Tcl_LinkVar)
Asynchronous Event Handlers (Tcl_AsyncCreate)
Adding Functions to expr Command (Tcl_CreateMathFunc)
Custom tclAppInit Routine (Tcl_AppInit)
Custom main Routine (Tcl_Main)
Via Pipes (open)
exec Command (exec)


The last two do not provide nearly the same level of integration as those near the top of the list, but they are necessary if you do not have access to the source code.

Supported Platform

This section contains information about Tcl 8.0 and Tk 8.0, the most recent version of Tcl/Tk. They were originally released on August 18, 1997 and the most recent patch releases (8.0.3) were made on September 3, 1998.

When you download Tcl and Tk you get two programs, wish and tclsh, supporting script libraries, and on-line reference documentation. These programs are gene ral purpose platforms for writing applications with Tcl. Wish includes the graphic al user interface toolkit Tk. The packages are ready to use after installation.

Tcl 8.0 and Tk 8.0 run on most releases of the following operating systems:
Windows 95 Windows NT Solaris and SunOS Linux HP-UX SGI IRIX Digital Unix AIX SCO Unix Most other Unix-like operating systems Macintosh (68K and Power Mac) Pre-compiled releases are available for different Linux distribution.


.

Safe-Tk and the Browser Plug-In

The main application of Safe-Tk is the Tcl/Tk plug-in for Web browsers like Netscape Navigator and Internet Explorer. Safe-Tk supports network applets that display user interfaces. The main vehicle for Safe-Tk is a plug-in for Netscape Navigator and Internet Explorer. The plug-in supports Tcl applets, or Tclets, that are downloaded from the Web server and execute inside a window in a Web browser. For the most part Tcl/Tk applications can run unchanged in the plug-in. However, security policies place some restrictions on Tclets. The plug-in supports multiple security policies, so Tclets can do a variety of interesting things in a safe manner.

There are two versions of the browser plug-in. Version 1 uses Tcl 7.7 and Tk 4.3, which were not released by themselves. Instead of providing wish and tclsh, only the shared libraries needed by the plug-in were distributed. These versions of Tcl and Tk had support for application embedding and some improvements in Safe-Tcl that later appeared in Tcl/Tk 8.0

Version 2 of the plug-in uses Tcl/Tk 8.0. You can configure the plug-in to use an existing wish application to host the Tcl applets, or the plug-in can load the Tcl/Tk shared libraries and everything runs in the browser process. You can use a custom wish that has extensions built in or dynamically loaded. This gives intranet applications of the plug-in the ability to access databases and other services that are not provided by the Tcl/Tk core. With the security policy mechanism you can still provide mediated access to these resources. .

Tk in Child Interpreters

A child interpreter starts out with the core Tcl commands. It does not include Tk or any other extensions that might be available to the parent interpreter. This is true whether or not the child interpreter is declared safe. You add extensions to child interpreters by using a form of the load command that specifies an interpreter:

load {} Tk child

Normally, load takes the name of the library file that contains the extension. In this case, the Tk package is a static package that is already linked into the program (e.g., wish or the plug-in), so the file name is the empty string. The load command calls the Tk initialization procedure to register all the Tcl commands provided by Tk.

Embedding Tk Windows

By default, a slave interpreter that loads Tk gets a new top-level window. Tk 8.0 supports a -use command line option that directs Tk to use an existing window as dot. You can use this to embed an application within another, but typically it is used with child interpreters. To pass -use to a child interpreter, you need to define the argv variable inside that interpreter before you load Tk:

interp eval child [list set argv [list -use [winfo id win]]

interp eval child [list set argc 2]
Passing -use to a safe interpreter is handled automatically by the safe::loadTk procedure.

The Browser Plug-In

The HTML <EMBED> tag is used to put various objects into a Web page, including a Tcl program. For example:
< EMBED src=eval.tcl width=400 height=300>
The width and height are interpreted by the plug-in as the size of the embedded window. The src specifies the URL of the program. These parameter names (e.g., width) are case sensitive and should be lowercase. In the above example, eval.tcl is a relative URL, so it should be in the same directory as the HTML file that has the EMBED tag. The window size is fixed in the browser, which is different than normal toplevels in Tk. The plug-in turns off geometry propagation on your main window so your Tclet stays the size allocated.

UNIX Configuration
Netscape looks in each user's /netscape/plugins for the shared libraries that implement plug-ins. It also looks in a plugins directory under its main directory, which will vary from site to site. You can define a search path for plug-ins with the NXP_PLUGIN_PATH environment variable. The plug-in script library is in /tclplug/2.0/plugin. You can change this default location by setting the TCL_PLUGIN_DIR environment variable. Once the plug-in finds its script library, it assumes the Tcl and Tk script directories, the security policies, and the trust map are in peer directories.

Windows Configuration The default location for plug-ins is in the PLUGINS directory of the Netscape installation. The Tcl/Tk plug-in also works in Internet Explorer from the same location. The script libraries are found under C:\TCLPLUG\2.0. You can change this location by setting the registry variable Software\Sun\Tcl Plugin\2.0\Directory.

Macintosh Configuration As of this writing the Macintosh plug-in is only available in the 1.0 version. The 2.0 version is expected in the next few months.

.

.

Syntax Rules of Tcl/Tk in Advance

It describes the basic mechanisms used by the Tcl interpreter: substitution and grouping. It touches lightly on the following Tcl commands: puts, format, set, expr, string, while, incr, and proc. 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.

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 than some other programming languages you may already be familiar with, so it is worth making sure you understand the basic concepts.


Tcl Commands


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., space or tab) is used to separate the command name and its arguments, and a newline or semicolon is used to terminate a command. The arguments to a command are just strings.


Tcl has syntax for grouping, which allows multiple words in one argument, and substitution, which is used with programming variables and nested command calls. The Tcl interpreter does grouping first, then substitutions, and finally it calls the command. It is up to the command to interpret its arguments.

Hello, World
! 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. 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.


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

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 is a little different, but not much.


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.
Command substitution.
set len [string length foobar] 6
In the example, the nested command is:
string length foobar

This command returns the length of the string foobar. The nested command runs first. 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 their result can be used in arguments to the outer command.

Math Expressions
The Tcl interpreter itself does not evaluate math expressions. Instead, the expr command is used to evaluate math expressions. The interpreter treats expr just like any other command, and it leaves the expression parsing up to the expr implementation. 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.

The implementation of expr takes all its arguments, concatenates them into a single string, and then parses the string as a math expression. After expr computes the answer, the answer is formatted into a string and returned:

Simple arithmetic.

expr 7.2 / 4

1.8

You can include variable references and nested commands in math expressions. The following example uses expr to add 7 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:

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 55 will do quoting for you automatically.

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 done 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.

You can also use backslash sequences to specify characters with their hexadecimal or octal value:

set escape \0x1b
set escape \033 The value of variable escape is the ASCII ESC character, which has character code 27.

A common use of backslashes is to continue long commands on multiple lines. This is necessary because a newline terminates a command unless an argument is being grouped


A backslash as the last character in a line is converted into a space. In addition, all the white space at the beginning of the next line is replaced by this substitution. The backslash in the next example is required; otherwise the expr command gets terminated by the newline after the plus sign. Continuing long lines with backslashes. set totalLength [expr [string length $one] + \ [string length $two]]

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. 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].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 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.

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]." In the next example the last argument is a nested command.

There is no need to explicitly group the nested command because the Tcl parser treats the whole nested command as part of the group. puts stdout [string length $s] In general, you can place a bracketed command or variable reference anywhere. The following computes a command name: [findCommand $x] arg arg

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.

Embedded command and variable substitution.

set x 7; set y 9 puts stdout $x+$y=[expr $x + $y] => 7+9=16 In the example 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: 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 can 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. Note that it is never necessary to explicitly group a nested command with double quotes if it makes up the whole argument. The following is a redundant use of double quotes: puts stdout "[expr $x + $y]"

Procedures

Tcl uses the proc command to define procedures. Once defined, a Tcl procedure is used just like any of the 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 tutorialbegins procedure names with uppercase letters and it begins variable names with lowercase letters. Good programming style is important as your Tcl scripts get larger.

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 only defined during execution of Diag. . It is not really necessary to use the variable c in this example.

The procedure could 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 prodecure. 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 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.

A Factorial Example
To reinforce what we have learned so far, here is a longer example that uses a while loop to compute the factorial function: 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
T he 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 evaluates the boolean expression, and then executes the body if the expression is true (non-zero).

The while command continues to test the expression and evaluate the command body until the expression is false (zero). 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 has to 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 have to escape the newline with a backslash: while {$i < $x} \ { set product ... } Always group expressions and command bodies with curly braces. 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 } 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. 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.

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 only contain 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. 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 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. Using info to determine if a variable exists. if {![info exists foobar]} { set foobar 0 } else { incr foobar } In Chapter 7, page 80, there is an example that 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, six significant digits. This 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: Controlling precision with tcl_precision. expr 1 / 3 => 0 expr 1 / 3.0 => 0.333333 set tcl_precision 17 => 17 expr 1 / 3.0 # The trailing 1 is the IEEE rounding digit => 0.33333333333333331 In Tcl 8.0 and later versions the overhead of conversions is eliminated in most cases by the built-in compiler.

The use of tcl_precision is also eliminated so values are always printed with full precision. 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 . 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"} { ... }

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.

You may see uses of expr that group the expression into one argument, which was necessary in early versions of Tcl: set y [expr {$x + $y}] ColdFusion Application Server delivers high performance Web applications that can scale to meet the needs of high volume sites. Multi-threaded Service - Rely on the multi-threaded service architecture to provide an application platform that can scale linearly with multiple processors on either Intel Win32 or SPARC Solaris. Web Server API Support -
Deliver applications with any major Web server using high performance server APIs including NSAPI, WSAPI, ISAPI and the Apache API.


 

Socket Programming

Here you will find that how to use sockets for programming network clients and servers. Advanced I/O techniques for sockets are described, including non-blocking I/O and control over I/O buffering. Tcl command: socket. Sockets are network communication channels. The sockets described in this chapter use the TCP network protocol, although you can find Tcl extensions that create sockets using other protocols.

TCP provides a reliable byte stream between two hosts connected to a network. TCP handles all the issues about routing information across the network, and it automatically recovers if data is lost or corrupted along the way. TCP is the basis for other protocols like Telnet, FTP, and HTTP.

A Tcl script can use a network socket just like an open file or pipeline. Instead of using the Tcl open command, you use the socket command to open a socket. Then you use gets, puts, and read to transfer data.

The close command closes a network socket. Network programming distinguishes between clients and servers. A server is a process or program that runs for long periods of time and controls access to some resource. For example, an FTP server governs access to files, and an HTTP server provides access to hypertext pages on the World Wide Web.

A client typically connects to the server for a limited time in order to gain access to the resource. For example, when a Web browser fetches a hypertext page, it is acting as a client. The extended examples in this chapter show how to program the client side of the HTTP protocol.

A client opens a socket by specifying the host address and port number for the server of the socket. The host address gives the network location (i.e., which computer) and the port selects a particular server from all the possible servers that may be running on that host. For example, HTTP servers typically use port 80, while FTP servers use port 20. The following example shows how to open a client socket to a Web server

 

Conclusion

It runs on many platformsVersions exist for UNIX (Linux... of course), Windows and Macintosh. Except for a few platform differences, your Tcl scripts will run the same way on all systems. It is interpreted You can execute your code directly, without compiling and linking (though Tcl compilers are available).

It is extensible It's easy to add your own commands to extend the Tcl language. You can write your commands in C or Tcl. It is embeddable in your applications The Tcl interpreter is merely a set of C functions that you can call from your code.

This means you can use Tcl as an application language, much like a macro language for a spreadsheet application.

Return to the top of the page

Now that you've gotten free know-how on this topic, try to grow your skills even faster with online video training. Then finally, put these skills to the test and make a name for yourself by offering these skills to others by becoming a freelancer. There are literally 2000+ new projects that are posted every single freakin' day, no lie!


Previous Article

Next Article


Natalia's Comment
It's like you're on a msiison to save me time and money!
25 Wed Apr 2012
Admin's Reply:

That's part of helping the humanity Natalia . We're on a mission to provide computer know-how to those less fortunate. To guys and gals like ourselves who were never cut-out or couldn't afford university education.