Chapter 2. Running Tcl Programs

This chapter describes how to use the Tcl interpreter interactively and in batch mode. Tcl is an interpreted language, so Tcl commands must be executed by an interpreter, tclsh, instead of being compiled and then executed directly. You can use tclsh interactively, allowing you to enter commands and see their results immediately. You can also save your Tcl commands to a file, called a command file (imaginative name, yes?) or script, and have the Tcl interpreter execute the script. After you become familiar with Tcl’s simple syntax, I think you will find it much more efficient to save your scripts in a file and execute them by passing the command file to the interpreter.

Invoking the Interpreter

To start the Tcl interpreter, tclsh, just type tclsh at a command prompt and press Enter (on Windows, select Start → All Programs → ActiveState ActiveTcl 8.4.14.0 → Tclsh84). If you invoke it with no arguments, tclsh runs interactively. In interactive mode, tclsh reads commands from stdin (a common abbreviation for standard input, which is ordinarily the keyboard) and displays the output of those commands to stdout (standard output, usually your display). Figures 2.1, 2.2, and 2.3 show tclsh running interactively on Linux, OS X, and Windows, respectively.

Running tclsh on a Linux system.

Figure 2.1. Running tclsh on a Linux system.

Running tclsh on an OS X system.

Figure 2.2. Running tclsh on an OS X system.

Running tclsh on a Windows system.

Figure 2.3. Running tclsh on a Windows system.

The puts command writes its argument, Hello, Tcl/Tk World! in this case, followed by a newline to stdout (actually, puts is more powerful than this, as you’ll learn in Chapter 8, “Accessing Files and Directories”).

The default tclsh command prompt is %. This prompt means that the interpreter is waiting for a command to execute. A second prompt exists, referred to as the secondary or input prompt. The interpreter displays the input prompt when it is waiting for additional input to complete a command. You’ll learn more about the input prompt in the next section.

When you are finished with your Tcl session, type exit and press Enter. As it happens, exit is a Tcl command, so it should work regardless of the operating system on which you are using Tcl. The interpreter also exits if it encounters an end-of-file (EOF) condition. EOF is operating system-specific: Linux and OS X users can send the EOF signal by pressing Ctrl-D. Windows users can press Ctrl-Z (Alt-F4 will close the window, but it isn’t really an EOF signal per se). However, because EOF is operating system-specific, I encourage you to use the exit command so you and your Tcl usage is not tied to or dependent upon platform-specific idioms.

Executing Tcl Commands Interactively

Now that you know how to start and stop the Tcl interpreter (referred to hereafter as tclsh), you probably want to know how to execute commands, right? Well, due to poor planning on my part, you already know because I told you in the previous section: start tclsh with no arguments to enter interactive mode and then start typing commands.

By default, the input prompt is unset. If you want to set it, execute the following command while running the interpreter:

set tcl_prompt2 {puts -nonewline "> "}

This command sets the value of the special Tcl variable tcl_prompt2, which controls the appearance of tclsh’s secondary prompt, to > (that’s a right angle bracket followed by a single space). The primary or command prompt can be modified by setting the value of tcl_prompt1. The input prompt is useful because it is a visual cue that your command is incomplete. If you start typing a Tcl command but don’t complete it, the interpreter will display “>” and then wait for you to enter the text required to complete the command (shown in the following example). You’ll learn more about variables in the next chapter, so just take this at face value for the time being.

% set tcl_prompt2 {puts -nonewline "> "}
puts -nonewline "> "
% puts
> "Hello, Tcl/Tk World!"
Hello, Tcl/Tk World!

In the example, I typed a puts command followed by , which tells the interpreter that the puts command is continued on the next line. On the next line, tclsh displayed the input prompt and then waited for input to complete the command. I completed the command by typing puts’ argument, "Hello, Tcl/Tk World!", and pressing Enter. The interpreter then executed the command and displayed the requested output.

Tip: Setting tcl_prompt2 Automatically

Tip: Setting tcl_prompt2 Automatically

Even though I don’t use tclsh interactively very often, I prefer to have an input prompt. Rather than typing set tcl_prompt2 {puts "> "} each time I start tclsh, I put this command in the .tclshrc configuration file in my home directory. If you are familiar with Linux or UNIX, the file would be $HOME/.tclshrc (see example-tclshrc in this chapter’s code directory on the Web site). If this file exists, tclsh reads it and executes the contents as a Tcl script. The behavior is the same for OS X and Windows. On OS X the file must also be named .tclshrc and located in your home directory; on Windows, the file must be named tclshrc.tcl and stored in your %HOME% directory. The typical use of tclshrc is to customize tclsh’s run-time behavior, such as customizing the prompts, but you can use tclshrc to execute any arbitrary set of commands you want executed each time you start tclsh in interactive mode.

You can execute any valid Tcl command in interactive mode. The next example shows a few of the commands you can use. Feel free to try them yourself to become familiar with tclsh’s admittedly Spartan interface. Don’t worry about the details of the commands right now. I’ll cover every command you see here in greater detail in later chapters.

% puts [clock format [clock seconds] -format {%A, %B %e, %Y}]
Saturday, April 7, 2007
% puts "You are using Tcl version $tcl_patchLevel"
You are using Tcl version 8.4.12
% puts "2 * 10 = [expr 2 * 10]"
2 * 10 = 20
% for {set i 0} {$i <= 5} {incr i} {puts "sine of $i is [expr sin($i)]"}
sine of 0: 0.0
sine of 1 is 0.841470984808
sine of 2 is 0.909297426826
sine of 3 is 0.14112000806
sine of 4 is -0.756802495308
sine of 5 is -0.958924274663
% puts My name is Kurt
wrong # args: should be "puts ?-nonewline? ?channelId? string"

The first command uses Tcl’s clock command (twice) to retrieve, format, and display the current date. The second command prints the value of another special Tcl variable, tcl_patchLevel, which stores the version of Tcl that you are running. The third command illustrates how to perform mathematical calculations using the expr command. The fourth command uses an iterative loop command, for, to calculate the sine of each integer between 0 and 5. So far, so good.

The last command, puts My name is Kurt, has a deliberate syntax error so you can see how tclsh behaves when you make a mistake. I executed the puts command with the wrong number of arguments; puts accepts one argument, the string to display, but I passed four arguments, My, name, is, and Kurt. To help me correct my mistake, puts displays the correct syntax. In this case, I could correct my error by enclosing the sentence in double quotes or braces (more about string-handling syntax in Chapter 4, “Strings, Strings, Everywhere Strings!”). The error message also shows you one of Tcl’s idiosyncrasies, the convention used to illustrate optional arguments in syntax diagrams: optional arguments are embedded between ? characters, rather than between a pair of brackets ([]). Tcl uses this convention because the language uses brackets for grouping arguments, as you’ll learn in the next chapter.

Using tclsh in interactive mode is ideal when you are first learning to use Tcl because you can type commands and see their results immediately. If you make a syntax error, you’ll see the error in context, which makes correcting it easy. Interactive mode is also handy for experimenting with new commands or features that you haven’t used before. Another advantage of tclsh’s interactive mode is that it lets you test small snippets of code before using them in a larger script. When I’m working on a program, I usually keep an interactive tclsh running in a separate window for just this purpose. Nevertheless, beginning with Chapter 3, I will use scripts almost exclusively because interactive mode is inefficient and inconvenient for writing and testing all but the shortest programs.

Creating Tcl Command Files

As you might have begun to see, interactive usage of tclsh, while convenient, quickly becomes tedious if you need to execute more than a few commands. If you need to execute the same set of commands frequently or repetitively, interactive use of tclsh will work, but is inefficient at best and infeasible at worst. Tcl command files, or scripts, are the solution. If you invoke tclsh with one or more arguments, it interprets the first argument as a Tcl command file or script and stores the second and following arguments as variables accessible in the script.

For example, suppose that you created a file named interactive.tcl and stored the five commands from the previous example in it. It might resemble the following script (see interactive.tcl in this chapter’s code directory):

puts "[clock format [clock seconds] -format {%A, %B %e, %Y}]"
puts "You are using Tcl version $tcl_patchLevel"
puts "2 * 10 = [expr 2 * 10]"
for {set i 0} {$i <= 5} {incr i} {puts "sine of $i is [expr sin($i)]"}
puts My name is Kurt

To execute this script, invoke tclsh and pass the name of the script file, interactive.tcl, as the first argument to tclsh, as shown in the following example:

$ tclsh interactive.tcl
You are using Tcl version 8.4.12
2 * 10 = 20
sine of 0 is 0.0
sine of 1 is 0.841470984808
sine of 2 is 0.909297426826
sine of 3 is 0.14112000806
sine of 4 is -0.756802495308
sine of 5 is -0.958924274663
wrong # args: should be "puts ?-nonewline? ?channelId? string"
    while executing
"puts My name is Kurt"
    (file "interactive.tcl" line 5)

The output is the almost the same as the interactive session shown in the previous section. The exception is the nature of the error message shown while executing the fifth command, puts My name is Kurt. In addition to the error message from puts, tclsh shows you the command it was executing, the file in which the command was located, and the line number in the file. This information is invaluable when you are debugging a large program that consists of multiple files of tens, hundreds, or thousands of lines—imagine having to track down the offending command without these hints.

As you can see, using a script file is much more convenient than interactive tclsh usage. If you are using Tcl on a Linux, UNIX, or OS X system, it gets even easier because you can make the script itself executable by using special notation at the top of the script. Insert the text #!/usr/bin/tclsh as the first line of the script, then set the file’s executable bit. Thus, interactive.tcl would look like the following script (see interactive2.tcl in this chapter’s code samples):

#!/usr/bin/tclsh
puts "[clock format [clock seconds] -format {%A, %B %e, %Y}]"
puts "You are using Tcl version $tcl_patchLevel"
puts "2 * 10 = [expr 2 * 10]"
for {set i 0} {$i <= 5} {incr i} {puts "sine of $i is [expr sin($i)]"}
puts My name is Kurt

Note: Finding the Path to tclsh on Your System

Note: Finding the Path to tclsh on Your System

If you are using ActiveState ActiveTcl on OS X, the path to tclsh should be /usr/ local/bin/tclsh. You can use the shell command which tclsh to find the path to tclsh on your system. On my Ubuntu system, the output looks like the following:

$ which tclsh
/usr/bin/tclsh

However, on my OS X system, the result was:

$ which t1clsh
/usr/local/bin/tclsh

On Linux and OS X, set the execute bit as shown in the following command:

$ chmod 755 interactive2.tcl

Now you can execute the script without having to invoke tclsh specifically:

$ ./interactive2.tcl
Saturday, April 7, 2007
You are using Tcl version 8.4.12
2 * 10 = 20
sine of 0 is 0.0
sine of 1 is 0.841470984808
sine of 2 is 0.909297426826
sine of 3 is 0.14112000806
sine of 4 is -0.756802495308
sine of 5 is -0.958924274663
wrong # args: should be "puts ?-nonewline? ?channelId? string"
    while executing
"puts My name is Kurt"
    (file "./interactive2.tcl" line 7)

Unfortunately, executing Tcl scripts directly on Windows is not as easy as it is for Linux and OS X. The simplest (and least elegant) approach is to start a tclsh session and use the source command to invoke the script. You’ll learn more about the source command in Chapter 7, “Writing Tcl Procedures,” so what I’ll say in this chapter is that the source command reads its argument, a filename, and executes the contents of the specified file as a script (see Figure 2.4).

Use the source command to execute Tcl scripts on Windows.

Figure 2.4. Use the source command to execute Tcl scripts on Windows.

As you can see in Figure 2.4, I executed the command source interactive.tcl, which read the contents of the script and executed it in the current tclsh session. This approach is easy, but it isn’t terribly elegant for an application you want to deploy because few users will want to start a tclsh just to play your game.

Fortunately, you have two other options: creating a shortcut or a file association for files that have a .tcl extension. To create a shortcut, the target should resemble C:Tclin clsh84.exe "C:Documents and SettingskwallDesktopinteractive.tcl" (see Figure 2.5).

Create a shortcut to execute Tcl scripts on Windows.

Figure 2.5. Create a shortcut to execute Tcl scripts on Windows.

Of course, you need to replace C:Documents and SettingskwallDesktopinteractive.tcl with the path to your script. Using a shortcut is the appropriate way to make a deployed Tcl script self-executable, but it is less than ideal during development because you have to create a shortcut for each new script you write.

For development and learning purposes, the approach I recommend for making your Tcl script directly executable is to create a file association for the extension .tcl. Using My Computer or the Windows Explorer interface, create a new file type for .tcl, and add an “open” action. The command for the action should be something like "C:Tclin clsh84.exe" "%1" "%*" (see Figure 2.6).

Create a file association to execute Tcl scripts on Windows.

Figure 2.6. Create a file association to execute Tcl scripts on Windows.

The "%1" parameter is a placeholder for the name of the script you want to execute. The "%*" parameter represents all of the arguments passed to the script, if any. Once you have set up the association, you can double-click Tcl script files in Explorer to execute them.

Tip: Dealing with Spaces in Filenames

Tip: Dealing with Spaces in Filenames

If the path to the tclsh executable or to your Tcl script contains spaces, enclose the name in quotes.

The good news is that if you installed ActiveState’s ActiveTcl distribution as described in the previous chapter, the ActiveState installer created a file association for Tcl scripts (that is, for files with the .tcl extension) for you. The bad news is that the association is to the wish (more about wish in Chapter 9, “Understanding Tk Programming”) executable (C:Tclinwish84.exe, by default). To fix the association, change wish84.exe to tclsh84.exe.

There is one final gotcha with self-executing Tcl scripts on Windows to address. If you create a shortcut or use a file association, when the script ends, the tclsh window closes, making it difficult to see what the script has done. An easy workaround to prevent this is to add the command gets stdin as the very last line in your script, as shown in the following example. This command waits for you to type input and press Enter.

puts "[clock format [clock seconds] -format {%A, %B %e, %Y}]"
puts "You are using Tcl version $tcl_patchLevel"
puts "2 * 10 = [expr 2 * 10]"
for {set i 0} {$i <= 5} {incr i} {puts "sine of $i is [expr sin($i)]"}
gets stdin

For the purposes of this book, the idea is to pause the script until you press Enter. After you press Enter, tclsh exits and the window closes. There are better ways to pause Tcl scripts, which you will learn later, but gets stdin will suffice for the time being.

This chapter showed you how to use Tcl, or rather, how to use the Tcl interpreter, tclsh. Interactive tclsh sessions enable you to experiment with new or unfamiliar Tcl commands and play with small snippets of code. For any non-trivial program, though, it is much easier to create Tcl scripts that invoke tclsh directly, what I referred to as self-executing Tcl scripts. Making Tcl scripts self-executable in the Windows environment is a bit challenging and somewhat kludgy, an awkward side effect of the text-oriented nature of straight Tcl scripts. When you learn how to create graphical Tcl programs with Tk, you’ll see that Tcl, in its Tk skin, integrates smoothly into GUI environments.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.242.131