XPS-Q8
Tcl Manual
Grouping before substitution.
The point of this example is to show how the grouping decision for
puts
’s second
argument is made, before the command substitution is done. Even if the result of the
nested command contained spaces or other special characters, they would be ignored for
the purposes of grouping the arguments to the outer command. Grouping and variable
substitution interact the same as with grouping and command substitution. Spaces or
special characters in variable values do not affect grouping decisions because these
decisions are made before the variable values are substituted.
If you want the output to look more readable as in the example, with spaces around the
+
and
=
, then you must use double quotes to explicitly group the argument to
puts
:
puts
stdout
"$x + $y = [
expr
$x + $y]"
The double quotes are used for grouping in this case to allow the variable and command
substitution on the argument for
puts
.
2.2.6.3
Grouping Math Expressions with Braces
It turns out that
expr
performs its own substitutions inside curly braces. This is
explained in more detail on page 15. This effectively means that you can write
commands as listed below and still have substitutions on the variables in the expression
occur:
puts
stdout
"$x + $y = [
expr
{$x + $y}]"
2.2.6.4
More Substitution Examples
If you have several substitutions without white space between them, you can avoid
grouping with quotes. The following command
concat
applied to variables
a
,
b
, and
c
will concatenate them:
set
concat
$a$b$c
Again, if you want to add spaces, you’ll need to use quotes:
set
concat
"$a $b $c"
In general, you can place a bracketed command or variable reference anywhere. The
following computes a command name:
[findCommand $x]
arg arg
2.2.7
Procedures
Tcl uses the
proc
command to define procedures. Once defined, a Tcl procedure is
used just like any of other built-in Tcl command. The basic syntax to define a procedure
is:
proc
name arglist body
The first argument is the name of the procedure being defined. The second argument is
a list of parameters used by the procedure. The third argument is a
command body
that is one or more Tcl commands. The procedure name is case sensitive, and in fact it
can contain any character. Procedure names and variable names do not conflict with
each other. As a convention, this guide begins procedure names with uppercase letters
and variable names with lowercase letters. Adopting good programming conventions is
important as your Tcl scripts become larger.
Example 1–12: Defining a procedure.
proc
Diag {a b} {
set
c [
expr
sqrt
($a * $a + $b * $b)]
return
$c
}
puts
"The diagonal of a 3, 4 right triangle is [Diag 3 4]"
⇒
The diagonal of a 3, 4 right triangle is 5.0
The
Diag
procedure defined in the above example computes the length of the
hypotenuse of a right triangle given the lengths of the legs. The
sqrt
function is one
EDH0307En1041 — 10/17
7