Version 17 of TCL programs for beginners

Updated 2004-06-15 21:12:35

Robert Abitbol The following basic programs written in TCL will give you a general introduction to the TCL syntax.

Code written by FW, LV, RS and BR. Many thanks to them!


Re: TCL syntax

aa - Tcl syntax isn't anything like C syntax. It's unlike the syntax of most other popular languages. It's supremely simple and straightforward. These basic programs serve mostly to show the absence of the kind of incantations that are required when programming in a language like C.


The Endekalogue and this page

aa I think the Endekalogue provides a more useful introduction to Tcl syntax, though it's likely that only someone who is already familiar with Tcl's quoting and substitution rules -- and who isn't burdened by trying to see it in a C-like context -- will understand it easily.

Robert Abitbol The Endekalogue is fine but most people understand better through examples like we provide here. In any case the Endekalogue and this page provide two different approaches: the best of both worlds. Both can co-exist. Thanks for your understanding.


Program # 1: Hello world. How to start and end a program; how to write something on the screen

  puts "Hello world!"
  exit 0

---> Save the program with the extension:

BR Two of the implied questions seem non-Tcl to me. You don't "end a program." You write libraries and in the end you call one of the library functions to start the program. In this example the library function is already written, it's called "puts". This is a good mental model in other languages too, BTW. Anyway, "exit 0" is superfluous, just like exit(0) in a C main() function would be as well.

LV Actually, an exit 0 is not superfulous in a C main function. Since Tcl exec treats non-zero return codes as if they were errors, terminating a program - regardless of the langauge - with an explict return of 0 when the program is terminating succesfully - ensures that the tcl exec doesn't raise a false error condition. However, note that it appears that tcl uses an exit code of 0, by default, if no exit is provided, so there is no real need to end a tcl program with an explicit exit.

Also you don't need to save the file with some pre-defined extension. The Tcl startup files are written in Tcl and they are called .tclshrc and .wishrc. Files with the extension .tml often contain Tcl code to produce HTML files etc. Tcl itself doesn't care what form the names of the files have.

LES: calling 'exit' at the end of every script can be a good habit. Especially if you use Windows and/or ActiveTcl and have .tcl files associated with wish. Scripts run with wish won't exit (and/or return output) until you close them manually if there is no exit command.

Robert Abitbol OK so I have the Tclkit and I want to execute a small function called Hello world. Can you tell how to go about it step by step?

LV Well, first I surely wouldn't call the function Hello World. While it is perfectly legal, why cause more grief than necessary?

Instead, what I would do is :

  1. create a text file called HelloWorld.tcl with the lines
        #! /path/to/tclkit
        puts "Hello World!"
        exit 0

Note that despite BR's comments above, I had no need to write a function and invoke it - I created a straight line program .

  1. Save the text file.
  2. From the command line, type:
        /path/to/tclkit HelloWorld.tcl

Note that if you are on Unix, there's no requirement to end the file name in .tcl . However, by doing so, then on Windows, one can associate the tclkit with the file. And Unix users who use a GUI file manager can do the same thing. And MacOS X users can do the same thing. Thus, instructions can be written in a more cross-platform manner.

Robert Abitbol I have the tclkit in c:\tcl kit\tclkit.exe. What do I put at the beginning of the program? c:\tcl kit\tclkit.exe ? And when I want to run the file I have coded, I'll copy it in the buffer than paste it in c:\tcl kit\tcl kit.exe?

LV On Windows, the first line is probably not relevant until you start using Cygwin or some other Unix emulation on MS-DOS package. It is my understanding that the default command processor on Windows ignores the #! line anyways. So on Windows, you would either type:

 tclkit.exe hellowworld.tcl

or you would go through whatever the steps are to associate tclkit as the program to use with files that end in .tcl .


Program # 2: an input is asked from the user; putting a variable in memory and printing it on the screen

  puts "Hey dude, how old might you be?"
  gets stdin Age
  puts "Dude, you are $Age years old but you look older."
  exit 0

Practice exercise:

Ask a person in which year he/she will retire.


Syntax of variables

So far as I know, variable names can contain pretty much anything, including spaces, and there's no requirement for the first letter to be capitalized. In fact, that would go against many programming "styles", where Capitalized and UPPERCASE and lowercase have specific implications. And it goes against the example given, which uses a variable named age with no upper case...or did until someone changed it to Age for no reason I can see.

BR Variables can have any string as their name. But to use the usual $name syntax, you want to restrict yourself to latin characters and digits.

For more information on Tcl variables, check out what kinds of variable names can be used in Tcl? and what kinds of variables can Tcl scripts use?


Program # 3: Very similar to # 2. But this time the variable will be a character or a series of characters (ex: a name)

FW: Not applicable, strings and ints are the same in Tcl. If you want to confirm the input was in integer form in the first example you can use [string is int].

LV Note that the requirements probably should read "this time the variable will hold a character...".

FW: Note that Tcl would do exit 0 automatically, unlike C, which would issue a warning without an explicit return. So in practice they would be left out, LV or put them in to make for a better comparison.

LV I put them in to make for a better comparison - but see my comments above about the cases where without the returns one could potentially end up with a problem.


What stdin stands for

FW: It stands for Standard Input. All programming languages support this, including C. It means the channel to receive input from (there's also an an stdout, and an stderr). This is usually commands typed in the console, but a program can be for example invoked by another program, which sends it data.


Program # 4: We ask a person his/her age. If it is under 20, we reply: "you are a child or a teenager". If it is 20 or over, we reply: "you are an adult now".

  puts "Hey dude, how old might you be?"
  gets stdin Age
  if {$Age < 20} { 
      puts "You are a child or a teen-ager"
  } else { 
      puts "You are an adult now" 
  }

[This is of course missing a load of error handling, right now all errors just cause a cryptic syntax error exception during execution.]

RS: Alternatively, one could write for the last 5 lines:

 puts "You are [expr {$Age<20? {a child or a teen-ager}: {an adult now}}]"

Robert Abitbol You would include all the ifs, else and put statements in one single statement. Very practical! : would mean "else"

You could say that : means "else", but you'd be glossing over the fact that it goes along with ? as part of the arithmetic if operator.'

aa - Watch out for hidden assumptions. Calling if and else "statements" betrays a fundamental lack of understanding of just how Tcl works. if is simply a command, just like any other command. Commands like Tcl's if and for might look familiar, but they're not built quite the way one usually thinks of them in a language like C. Read the documentation for if to see that it's a regular Tcl command with arguments.

In a smaller number of lines

 puts "Hey dude, how old might you be?"
 gets stdin Age
 puts "You are [expr {$Age<20? {a child or a teen-ager}: {an adult now}}]"

Program # 5: Very similar to program # 4 but a little more complex. We ask a person his/her age.

* If it is under 12, we reply: "you are a child".

* If it is between 13 and 19 we reply: "you are a teenager".

* Else we reply: "you are an adult now".'''

  puts "Hey dude, how old might you be?"
  gets stdin Age
  if {$Age < 12} {
    puts "You are a child"
  } elseif {$Age < 19} {
    puts "You are a teen"
  } else { 
    puts "You are an adult now" 
  }

In one statement

 puts "Hey dude, how old might you be?"
 gets stdin Age
 puts "You are a[expr {$Age < 12 ? " child" : ($Age < 19 ? " teen" : "n adult now")}]

Program # 6: Very similar to program # 5 but we introduce the syntax: between ... and ...

---> We ask a person his/her age.

* If it is between 0 and 12, we reply: "you are a child".

* If it is between 13 and 19 we reply: "you are a teenager".

* If is over 19 (else), we reply: "you are an adult now".

  puts "Hey dude, how old might you be?"
  gets stdin Age
  if ...{
    puts "You are a child"
  } if...{
    puts "You are a teen"
  } if { 
    puts "You are an adult now" 
  }

Huh? This code snippet makes no sense to me, and has errors galore when I cut and paste it into an interpreter. Is "between ..." some new 8.5 or 9.0 syntax for the if command? If so, this example doesn't do a very good job of illustrating it, because I don't see the word "between" anywhere. Also, I don't see how ...{ can do quoting, which seems to be implied by the rest of the example. This whole example has me shaking my head wondering what's going on.


This seems to be a use case for the comb pattern:

 puts "You are a(n) [comb $Age {child 13 teen 19 adult}]"

just to show (off) that functional programming can be put to surprising uses all over the place. In Tcl, you can code like in C, but maybe you shouldn't...


See also Endekalogue, Tcl cheat sheet and 99 bottles of beer.


Category Tutorial