85.24%
Search · Index

V.1 Tcl for Web Nerds Introduction

Evaluation and quoting


Each line of Tcl is interpreted as a separate command:
procedure_name arg1 arg2 arg3
Arguments are evaluated in sequence. The resulting values are then passed to procedure_name, which is assumed to be a system- or user-defined procedure. Tcl assumes that you're mostly dealing with strings and therefore stands some of the conventions of standard programming languages on their heads. For example, you might think that set foo bar would result in Tcl complaining about an undefined variable (bar). But actually what happens is that Tcl sets the variable foo to the character string "bar":
> tclsh
% set foo bar
bar
% set foo
bar
%

The first command line illustrates that the set command returns the new value that was set (in this case, the character string "bar"), which is the result printed by the interpreter. The second command line uses the set command again, but this time with only one argument. This actually gets the value of the variable foo. Notice that you don't have to declare variables before using them.

By analogy with Scheme, you'd think that we could just type the command line $foo and have Tcl return and print the value. This won't work in Tcl, however, which assumes that every command line invokes a procedure. This is why we need to explicity use set or puts.

Does this mean that you never need to use string quotes when you've got string literals in your program? No. In Tcl, the double quote is a grouping mechanism. If your string literal contains any spaces, which would otherwise be interpreted as argument separators, you need to group the tokens with double quotes:

% set the_truth Lisp is the world's best computer language
wrong # args: should be "set varName ?newValue?"
% set the_truth "Lisp is the world's best computer language"
Lisp is the world's best computer language
In the first command above, the Tcl interpreter saw that we were attempting to call set with seven arguments. In the second command, we grouped all the words in our string literal with the double quotes and therefore the Tcl interpreter saw only two arguments to set. Note a stylistic point here: multi-word variable names are all-lowercase with underscores separating the words. This makes our Tcl code very compatible with relational database management systems where underscore is a legal character in a column name.

In this example, we invoked the Unix command "tclsh" to start the Tcl interpreter from the Unix shell. Later on we'll see how to use Tcl in other ways:

  • writing a program file and evaluating it
  • embedding Tcl commands in Web pages to create dynamic pages
  • extending the behavior of the Web server with Tcl programs
For now, let's stick with typing interactively at the shell. You can keep evaluating Tcl commands at the % prompt until you exit the Tcl shell by evaluating exit.

To indicate a literal string that contains a space, you can wrap the string in double quotes. Quoting like this does not prevent the interpreter from evaluating procedure calls and variables inside the strings:

% set checking_account_balance [expr {25 + 34 + 86}]
145
% puts "your bank balance is $checking_account_balance dollars"
your bank balance is 145 dollars
% puts "ten times your balance is [expr {10 * $checking_account_balance}] dollars"
ten times your balance is 1450 dollars
The interpreter looks for dollar signs and square brackets within quoted strings. This is known as variable interpolation What if you need to include a dollar sign or a square bracket? One approach is to escape with backslash:
% puts "your bank balance is \$$checking_account_balance"
your bank balance is $145
% puts "your bank balance is \$$checking_account_balance \[pretty sad\]"
your bank balance is $145 [pretty sad]

If we don't need Tcl to evaluate variables and procedure calls inside a string, we can use braces for grouping rather than double quotes:

% puts {your bank balance is $checking_account_balance dollars}
your bank balance is $checking_account_balance dollars
% puts {ten times your balance is [expr {10 * $checking_account_balance}] dollars}
ten times your balance is [expr {10 * $checking_account_balance}] dollars
Throughout the rest of this book you'll see hundreds of examples of braces being used as a grouping character for Tcl code. For example, when defining a procedure or using control structure commands, conditional code is grouped using braces.

Keep it all on one line!

The good news is that Tcl does not suffer from cancer of the semicolon. The bad news is that any Tcl procedure call or command must be on one line from the interpreter's point of view. Suppose that you want to split up
% set a_very_long_variable_name "a very long value of some sort..."
If you want to have newlines within the double quotes, that's just fine:
% set a_very_long_variable_name "a very long value of some sort... 
with a few embedded newlines
makes for rather bad poetry"
a very long value of some sort...
with a few embedded newlines
makes for rather bad poetry
%
It also works to do it with braces
% set a_very_long_variable_name {a very long value of some sort... 
with a few embedded newlines
makes for rather bad poetry}
a very long value of some sort...
with a few embedded newlines
makes for rather bad poetry
%
but if you were to try
set a_very_long_variable_name 
"a very long value of some sort...
with a few embedded newlines
makes for rather bad poetry"
Tcl would interpret this as two separate commands, the first a call to set to find the existing value of a_very_long_variable_name and the second a call to the procedure named "a very long value...":
can't read "a_very_long_variable_name": no such variable
invalid command name "a very long value of some sort...
with a few embedded newlines
makes for rather bad poetry"
If you want to continue a Tcl command on a second line, it is possible to use the backslash to escape the newline that would otherwise terminate the command:
% set a_very_long_variable_name \
"a very long value of some sort...
with a few embedded newlines
makes for rather bad poetry"
a very long value of some sort...
with a few embedded newlines
makes for rather bad poetry
%
Note that this looks good as code but the end-result is probably not what you'd want. The second and third lines of our poem contain seven spaces at the beginning of each line. You probably want to do something like this:
% set a_very_long_variable_name "a very long value of some sort... 
with a few embedded newlines
makes for rather bad poetry"

 

 

Case Sensitivity, Poisonous Unix Heritage, and Naming Conventions

The great case-sensitivity winter descended upon humankind in 1970 with the Unix operating system.
% set MyAge 36
36
% set YearsToExpectedDeath [expr {80-$Myage}]
can't read "Myage": no such variable
%
Variables and procedure names in Tcl are case-sensitive. We consider it very bad programming style to depend on this, though. For example, you shouldn't simultaneously use the variables Username and username and rely on the computer to keep them separate; the computer will succeed but humans maintaining the program in the future will fail. So use lowercase all the time with underscores to separate words!

 

Procedures 

One of the keys to making a large software system reliable and maintainable is procedural abstraction. The idea is to take a complex operation and encapsulate it into a function that other programmers can call without worrying about how it works.

To define a procedures in Tcl use the following syntax:

proc name { list_of_arguments } {
body_expressions
}

This creates a procedure with the name "name." Tcl has a global environment for procedure names, i.e., there can be only one procedure called "foobar" in a Tcl system.

The next part of the syntax is the set of arguments, delimited by a set of curly braces. Each argument value is then mapped into the procedure body, which is also delimited by curly braces. As before, each statement of the procedure body can be separated by a semi-colon or a newline (or both). Here's an example, taken from the calendar widget component of the ArsDigita Community System:

proc calendar_convert_julian_to_ansi { date } {
set db [ns_db gethandle subquery]
# make Oracle do all the real work
set output [database_to_tcl_string $db \
"select trunc(to_date('$date', 'J')) from dual"]
ns_db releasehandle $db
return $output
}

As  you can see the variable "date" is set in the context of the procedure so you can address the value with "$date".

Here's the factorial procedure in Tcl:

% #this is good old recursive factorial
% proc factorial {number} {
if { $number == 0 } {
return 1
} else {
return [expr {$number * [factorial [expr {$number - 1}]]}]
}
}
% factorial 10
3628800
At first glance, you might think that you've had to learn some new syntax here. In fact, the Tcl procedure-creation procedure is called like any other. The three arguments to proc are procedure_name arglist body. The creation command is able to extend over several lines not because the interpreter recognizes something special about proc but because we've used braces to group blocks of code. Similarly the if statement within the procedure uses braces to group its arguments so that they are all on one line as far as the interpreter is concerned.

As the example illustrates, we can use the standard base-case-plus-recursion programming style in Tcl. Our factorial procedure checks to see if the number is 0 (the base case). If so, it returns 1. Otherwise, it computes factorial of the number minus 1 and returns the result multiplied by the number. The # character signals a comment.

Examine the following example:

% set checking_account_balance [expr {25 + 34 + 86}]
145
% puts "\nYour checking balance is \$$checking_account_balance.
If you're so smart, why aren't you rich like Bill Gates?
He probably has \$[factorial $checking_account_balance] by now."


Your checking balance is $145.
If you're so smart, why aren't you rich like Bill Gates?
He probably has $0 by now.
There are a few things to observe here:
  • The "\n" at the beginning of the quoted string argument to puts resulted in an extra newline in front of the output.
  • The newline after balance. did not terminate the puts command. The string quotes group all three lines together into a single argument.
  • The [factorial... ] procedure call was evaluated but resulted in an output of 0. This isn't a bug in the evaluation of quoted strings, but rather a limitation of the Tcl language itself:
    % factorial 145
    0

 


 Exercises

 

 1. Write the identity function (the I combinator), which simply returns its argument (any type of argument) unchanged:
# I :: alpha -> alpha
proc I {x} {...}
Examples:
I 12
=> 12
I foo
=> foo
I {string length abracadabra}
=> {string length abracadabra}

Why is this a useful function?

Answer

 

 2. Write the K combinator, which takes two arguments and always returns its first argument, unchanged:
# K :: alpha beta -> alpha
proc K {x y} {...}
Examples:
K 0 456
=> 0
K foo 1
=> foo

Why is this a useful function?

Answer

 

---

based on Tcl for Web Nerds