Tcl Intro

On the c.l.t newsgroup, it was noted that there was some interest in creating a Tcl Intro document in the same spirit as perl's perlintro [L1 ]. This is meant to be a quick-and-dirty kind of guide for those who already have a moderate amount of programming experience and are looking to jump in head-first with the help of a few ground rules and examples. Nothing is explained in detail, but there are a few links in the FOOTNOTES that point to other web pages and wiki articles that deal with issues that a new Tcl programmer might stumble into.

If you're noticing that this document looks a lot like a man page, you're dead on. It would be great if a reference like this could some day be included in the core Tcl distribution or a least a few batteries-included distributions as a man page. Some content (the footnotes in particular) does not follow standard wiki convention... that's because in the end, I'd like it to be portable to a number of different formats. But putting it up here on the wiki while it's still being written makes it easy for anyone to come along and make some constructive changes to it.

Very small portions of this document have been adapted from:

(If adapting portions of any of these references is out of line, please let me know and I'll remove the offending parts.)

Help is more than appreciated. Like all wiki pages, feel free to edit or add to anything here. I only humbly request that you stay true to the spirit of the document, which primarily means no detailed explanations. Subjects that fall outside of the scope of the Tcl core distribution ([incr Tcl], Tk, binary distributions) also fall outside the scope of this document. Please place all discussion between the lines delimiting this section and the document proper rather than within the document proper. Thanks.

--CJU


[Discussion goes here.]

LV How much, if any, of the following info made it into the Tcl 8.5 tcl tutorial? Is there a link that could be put here to a wiki page for info about the new tcl tutorial?


NAME

tclintro -- a brief introduction and overview of Tcl

DESCRIPTION

This document provides a quick introduction and overview of the structure and features of the Tcl programming language. (more explanation needed)

What is Tcl?

The name Tcl is derived from "Tool Command Language" and is pronounced "tickle." Tcl is an open-source, interpreted programming language that provides common facilities, such as variables, procedures, and control structures as well as many useful features that are not found in any other major language. Tcl runs on almost all modern operating systems such as Unix, Macintosh, and Windows. While Tcl is flexible enough to be used in almost any application imaginable, it does excel in a few key areas, including: automated interaction with external programs, embedding as a library into application programs, and of course plain old scripting.

Running Tcl Programs

Tcl is released as source code. If your operating system is Macintosh or Windows, a third-party binary package is usually the easiest way to install Tcl on your system. Instructions on how to run programs from binary releases are not included in this document--see the documentation included with your particular package for more information. The remainder of this document assumes that Tcl has been installed from source or by the vendor on a system with command line interface, such as Unix-like systems.

Tcl scripts are often executed via tclsh, a simple shell containing a Tcl interpreter. If tclsh is in your path, simply type its name on the command line. Tclsh takes one optional argument, a filename containing a Tcl script, followed by additional optional arguments that are passed directly to the script:

 $ tclsh progname.tcl arg1 arg2

You can also make your script executable using chmod u+x progname.tcl and then adding a line similar to the following line as the very first line of the file:

 #!/usr/local/bin/tclsh

(The above example assumes you have tclsh installed in the directory /usr/local/bin . If that is not the case on your system, replace the string /usr/local/bin with the name of the directory containing tclsh on your own machine.)

This will do for testing your own scripts, but more portable solutions exist. [1]

 #!/bin/sh
 # \
 exec tclsh "$0" ${1+"$@"}

Basic syntax overview

Tcl syntax is extremly simple in that each line consists of a single command followed by an any number of optional arguments.

command ?arg arg ...?

(See also https://www.tcl-lang.org/scripting/syntax.html for a brief syntax introduction. Feel free to borrow from that page - BW) (Thanks! I've actually been using your book as a reference for writing this. - CJU)

Example:

 puts "hello world"

If there is only one argument (delimited here by double quotes), the command puts prints the argument as a string to the standard output. A newline signals the end of a command and its arguments. Commands do not span across multiple lines unless the newline is contained within a pair of grouping characters (curly braces, brackets, or double quotes) or when escaped by a backslash. These are explained later. Multiple commands may be placed on a single line by separating them with a semicolon:

 puts "hello"; puts "world"

Comments start with a hash (or pound) symbol and run to the end of the line:

 # This is a comment

The # character must appear at the beginning of the comment. If you want to place a comment on the same line as a command to be executed, use a semicolon before the #:

 puts "hello"  ;# Print a greeting.

Like a command, comments cannot have unmatched braces inside them.[2] Unlike a command, whitespace is not mandatory between the first # and the rest of the comment:

 #This is a valid comment
 ### As is this

Variables

Variables in Tcl are untyped. The popular axiom, "everything is a string," means that data handling in Tcl is generally straight-forward and flexible. You set a variable with the set command, which has the following syntax:

set varName ?value?

For example

 set foo bar

sets the value of the variable foo to the string "bar". Variables do not need to be declared manually, they are brought into existance merely by assigning them some value. To retrieve the value of a variable, prefix the variable name with a dollar sign, like this:

 puts $foo

The string "bar" would be printed on standard output. This is the first example of substitution that we'll present. In the previous example, Tcl substitutes the variable foo for its value ("bar") then executes the puts command. Variable substitution can occur virtually anywhere except within curly braces, which we'll examine in a moment.

 set baz $foo
 puts $baz

The first command sets the value of baz to the value of foo and the second prints the value of baz to standard output.

Command Substitution

Command substitution works identically to variable substitution with the obvious exception that the result of a command is substituted rather than the value of a variable. For this example, we're going to use the clock seconds command, which returns (in theory) the number of seconds elapsed since the epoch. (This particular number isn't of any concern to us, we only want to see some kind of obvious command substitution in action.) The command being substituted is delimited by a set of square brackets, as shown:

 set result [clock seconds]
 puts $result

Grouping

Double quotes and curly braces are used to group strings together into a single argument. The primary difference between the two is that pairs of double quotes allow substitutions to occur within them, while sets of curly braces do not. The command:

 puts hello world ;# WRONG

would cause Tcl to emit an error because puts behaves differently depending on the number of arguments it receives. The following is correct:

 puts "hello world"

One could have also written:

 puts {hello world}

and gotten the same effect. Where you would see the difference, however, is when substitution comes into play. Suppose we have the following statements:

 set foo 5
 puts "The number is $foo"
 puts {The number is $foo}

The first puts command produces the statement "The number is 5" whereas the second produces "The number is $foo". The curly braces exist because there are many cases where the programmer does not want substitution to occur when the script is first evaluated, but at some later point. These principles hold true for command substitution as well.

Strings

For the most part, strings are handled just as we've seen in the previous sections. The built-in Tcl command library has a few commands for helping the programmer deal with strings. The string length command returns the number of characters that compose a particular string:

 set foo "hello world"
 puts [string length $foo]

The string index command returns a character at a particular location within a string:

 set foo "hello world"
 puts [string index $foo 6]

This prints the letter "w". There are many more operations that the string command can perform, see the man page for string to learn more.

Lists

Lists are values (often strings) which are grouped in a way that they can be easily manipulated by Tcl. Older versions of Tcl represented lists internally as strings with curly braces to delimit values, so that is a good way for the beginner to visualize them. The list command creates list from the arguments that it receives:

 set foo [list one two three]

Now $foo contains, "one two three". If this looks pointless, remember that list elements are delimited by white space. The following shows how to nest lists:

 set bar [list $foo four five six]

The variable $bar now contains the string, "{one two three} four five six". Levels of nesting are unlimited. Remember, also, that a list element with whitespace becomes its own list:

 set e1 one
 set e2 "element two"
 set e3 three
 set foo [list $e1 $e2 $e3]

$foo will contain, "one {element two} three"

lindex returns a list element, just like string index did for characters.

 set bar [lindex $foo 0]
 puts [lindex $foo 1]

Thus $bar contains "one", and puts prints "element two".

You can insert more elements into lists using linsert. The original is not modified, unless you do it yourself. Assume $foo to still contain "one {element two} three".

 puts $foo
 puts [linsert $foo 1 "one-and-half"]
 puts $foo
 set foo [linsert $foo 1 "one-and-a-quarter" "one-and-half" "seven-quarters"]

Now $foo will contain, "one one-and-a-quarter one-and-half seven-quarters {element two} three".

Arrays

Arrays are Tcl's assoiciative memory. Regard this:

 set "lunch(Italian)" "Pizza"
 set "lunch(Greek)" "Gyros"
 set "lunch(Chinese)" "Chop Suey"
 puts [array size lunch]
 foreach i [array names lunch] {
     puts "$i lunch is $lunch($i) today."
 }

After the three set commands, the array size will be 3, and the foreach loop will print each entry.

Variable scoping

[add text to briefly describe]

Conditional and looping constructs

[add text to briefly describe]

Expressions

Unlike many other programming languages, Tcl does not attempt to interpret the arguments of a command as (semi-)mathematical expressions. Condition arguments (of if, while, etc.) are interpreted as expressions because conditions are expressions more often than not, but that is part of the semantics of those commands. In general when you want to evaluate an expression, you do this using the expr command.

[add text to briefly describe]

Files and I/O

[add text to briefly describe]

Regular Expressions

[add text to briefly describe]

Writing procedures

[add text to briefly describe]

Using Tcl Extensions

[add text to briefly describe]

  • installing a tcl script extension
  • compiling a source extension to binary
  • installing a binary extension
  • package require

FOOTNOTES

  1. exec magic: [L2 ]
  2. Why can I not place unmatched braces in Tcl comments: [L3 ]


[Category Documentation|Category Tutorial]