command argument1 argument2 ?option1? ?option2? …
This means that the (fictitious) Tcl command, command, takes two mandatory arguments, plus some
optional arguments that may be used to change its behavior. You’ll find this type of syntax used in the
official Tcl/Tk documentation.
Variables and Values
Tcl deals essentially with strings and groups of strings. Most values can be dealt with as strings, and
where necessary, Tcl will automatically convert between types, for example to perform arithmetic on
numbers. To assign to a variable, creating the variable if necessary, we use the set command. You can
follow the rest of this section as a walk-through example in the Tcl shell.
$ tclsh
% set a 123
123
% set hello there
there
%
Variable names are case-sensitive and can be any length. Special characters (such as whitespace) in
variable names and values need to be quoted, which you do by enclosing the name or value in double
quotes. As in the UNIX shell, you need to take care with quoting. We’ll learn more about different quoting
methods in Tcl shortly.
% set "hello there" "fare well"
fare well
%
To examine the current value of a variable, use the set command again, but this time don’t give it a value
argument.
% set hello
there
% set "hello there"
fare well
%
When using Tcl interactively like this, the interpreter prints the result of each command. In the case of the
set command, we see the variable’s new value printed after an assignment, or the variable’s present
value if no new value is given. This is because the set command itself returns the current value of the
variable.
To use the value of a variable in another command, we prefix its name with a $, just as we do in the UNIX
shell. In our example program, we assigned a string to the variable s and then used it in the puts
command, which wrote it to the screen, by referring to it as $s. You can use braces to quote variable
names that contain spaces.
% puts $a
123
% puts [expr $a + $a]
246
% puts ${hello there}
fare well
%
To use the result of one command in another, we place the command in square brackets, as in the second
example above. This causes the Tcl interpreter to execute the command and return a result that is used in
its place. This is very like the way we use $(command) in the UNIX shell. In the same example, we use the
expr command, which evaluates a Tcl expression and returns the result.
评论0
最新资源