For a scripting language, Tcl has a very simple syntax. Here it is:
cmd arg arg arg
$foo
foo
.
[clock seconds]
"some stuff"
{some stuff}
\n
Below is a Tcl command that prints out the current time. It uses three
Tcl commands: set
, clock
, and puts
.
The set
command does variable assignment. The clock
command manipuates time values. The puts
command prints
values.
set seconds [clock seconds] puts "The time is [clock format $seconds]"
The seconds variable isn't really needed in the example. You could do it with one command:
puts "The time is [clock format [clock seconds]]"
The Tcl syntax is used to guide the Tcl parser through two steps:
puts
command.
$foo
with the value of the variable foo
, and it replaces nested
comamnds with their result. The fact that substitutions are done after
grouping is crucial. It means that funny values do not mess up the
structure of commands.
Here is another example.
Here we see curly braces used to group arguments without doing any substitutions. What's really going on is that the Tcl parser knows nothing special about theset i 0 while {$i < 10} { puts "$i sqared = [expr $i*$i]" }
while
command. It treats
it like any other command. The braces group two arguments, the boolean
expression that controls the loop, and the commands in the loop body.
It is the implementation of the while
command that knows
that the first argument is an expression, and the second argument is
more Tcl commands.
We also see two math expressions: the boolean comparison, and the multiplication.
In Tcl you use the expr
command to do math evaluation.
There are other commands, like while
, that treat some
of their arguments as expressions, too.
The final thing Tcl does is call someone else to do all the hard work.
We've seen that it uses expr
to do math, puts
to do output, and set
to do variable assignment. These
Tcl commands are all implemented by a C procedure that has registered
itself with Tcl. The C command procedures take the string arguments
from the Tcl command, and they return a new string as their result.
It is very easy to write C command procedures, and there are lots of
them that do everything from accessing databases to creating graphical
user interfaces. Tcl, the language, doesn't really know what the commands
do. It just groups arguments, substitutes results, and dispatches commands.
Here is the factorial procedure.
proc fac {x} { if {$x <= 0} { error "Invalid argument $x: must be a positive integer" } elseif {$x == 1} { return 1 } else { return [expr $x * [fac [expr $x-1]] } }