Version 4 of Talk to me, Tcl

Updated 2005-12-23 23:25:21

Richard Suchenwirth 2005-09-04 - The following is a chapter in the WikiBook http://en.wikibooks.org/wiki/Programming:Tcl I'm currently working on (mostly by pasting, and polishing, pages from this Wiki :^) Everybody is welcome to check it out. But I'll continue to put my pages on Tcl here first, and copy them to the WikiBook where appopriate.

RLH Thanks for helping to flesh out the wikibook. RS Welcome - it has grown from less-than-a-page to a kind of brochure by now :)

=== Interaction with Tcl ===

Tcl itself is quite a good teacher. Don't be afraid to do something wrong, you'll most often get a helpful error message. When tclsh is called with no arguments, it starts in interactive mode and displays a "%" prompt. You type something in, and see what comes out (the result, or an error message). Here's a commented session transcript:

 % hello
 invalid command name "hello"

OK, so we're supposed to type in a command. Although it doesn't look so, here's one:

 % hi
     1  hello
     2  hi

Interactive tclsh tries to guess what we mean, and "hi" is the umambiguous prefix of the "history" command, whose results we see here. Another command worth remembering is "info":

 % info
 wrong # args: should be "info option ?arg arg ...?"

Error message: it tells us there should be at least one option, and optionally more arguments.

 % info option
 bad option "option": must be args, body, cmdcount, commands, complete, default,
 exists, functions, globals, hostname, level, library, loaded, locals, nameofexecutable,
 patchlevel, procs, script, sharedlibextension, tclversion, or vars

Another helpful error: "option" is not an option, but the valid ones are listed. To get information about commands, it makes sense to type the following:

 % info commands
 tell socket subst open eof pwd glob list exec pid auto_load_index time unknown
 eval lrange fblocked lsearch auto_import gets case lappend proc break variable llength 
 auto_execok return linsert error catch clock info split array if fconfigure concat
 join lreplace source fcopy global switch auto_qualify update close cd for auto_load
 file append format read package set binary namespace scan trace seek while flush
 after vwait uplevel continue foreach lset rename fileevent regexp upvar unset
 encoding expr load regsub history interp exit puts incr lindex lsort tclLog string

Oh my, quite many... How many?

 % llength [info commands]
 86

Now for a more practical task - let's let Tcl compute the value of Pi.

 % expr acos(-1)
 3.14159265359

Hm.. can we have that with more precision?

 % set tcl_precision 17
 17
 % expr acos(-1)
 3.1415926535897931

Back to the first try, where "hello" was an invalid command. Let's just create a valid one:

 % proc hello {} {puts Hi!}

Silently acknowledged. Now testing:

 % hello
 Hi!

Category Tutorial