Monday, November 17, 2008

Procedures

Tcl uses the proc command to define procedures. Once defined, a Tcl procedure
is used just like any of the other built-in Tcl commands. 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 to 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 characters.
Procedure names and variable names do not conflict with each other. As a
convention, this book begins procedure names with uppercase letters and it
begins variable names with lowercase letters. Good programming style is important
as your Tcl scripts get larger. Tcl coding style is discussed in Chapter 12.
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 example computes the length of the diagonal
side of a right triangle given the lengths of the other two sides. The sqrt
function is one of many math functions supported by the expr command. The
variable c is local to the procedure; it is defined only during execution of Diag.
Variable scope is discussed further in Chapter 7. It is not really necessary to use
the variable c in this example. The procedure can also be written as:
proc Diag {a b} {
return [expr sqrt($a * $a + $b * $b)]
}
The return command is used to return the result of the procedure. The
return command is optional in this example because the Tcl interpreter returns
the value of the last command in the body as the value of the procedure. So, the
procedure could be reduced to:
proc Diag {a b} {
expr sqrt($a * $a + $b * $b)
}
Note the stylized use of curly braces in the example. The curly brace at the
end of the first line starts the third argument to proc, which is the command
body. In this case, the Tcl interpreter sees the opening left brace, causing it to
ignore newline characters and scan the text until a matching right brace is
found. Double quotes have the same property. They group characters, including
newlines, until another double quote is found. The result of the grouping is that
12 Tcl Fundamentals Chap. 1
the third argument to proc is a sequence of commands. When they are evaluated
later, the embedded newlines will terminate each command.
The other crucial effect of the curly braces around the procedure body is to
delay any substitutions in the body until the time the procedure is called. For
example, the variables a, b, and c are not defined until the procedure is called, so
we do not want to do variable substitution at the time Diag is defined.
The proc command supports additional features such as having variable
numbers of arguments and default values for arguments. These are described in

No comments: