www.gibmonks.com




  Previous section   Next section

Practical Programming in Tcl & Tk, Third Edition
By Brent B. Welch

Table of Contents
Chapter 7.  Procedures and Scope


The proc Command

A Tcl procedure is defined with the proc command. It takes three arguments:

proc name params body

The first argument is the procedure name, which is added to the set of commands understood by the Tcl interpreter. The name is case sensitive and can contain any characters. Procedure names do not conflict with variable names. The second argument is a list of parameter names. The last argument is the body of the procedure.

Once defined, a Tcl procedure is used just like any other Tcl command. When it is called, each argument is assigned to the corresponding parameter and the body is evaluated. The result of the procedure is the result returned by the last command in the body. The return command can be used to return a specific value.

Procedures can have default parameters so that the caller can leave out some of the command arguments. A default parameter is specified with its name and default value, as shown in the next example:

Example 7-1 Default parameter values.
proc P2 {a {b 7} {c -2}} {
   expr $a / $b + $c
}
P2 6 3
=> 0

Here the procedure P2 can be called with one, two, or three arguments. If it is called with only one argument, then the parameters b and c take on the values specified in the proc command. If two arguments are provided, then only c gets the default value, and the arguments are assigned to a and b. At least one argument and no more than three arguments can be passed to P2.

A procedure can take a variable number of arguments by specifying the args keyword as the last parameter. When the procedure is called, the args parameter is a list that contains all the remaining values:

Example 7-2 Variable number of arguments.
proc ArgTest {a {b foo}args} {
   foreach param {a b args} {
      puts stdout "\t$param = [set $param]"
   }
}
set x one
set y {two things}
set z \[special\$
ArgTest $x
=> a = one
   b = foo
   args =
ArgTest $y $z
=> a = two things
   b = [special$
   args =
ArgTest $x $y $z
=> a = one
   b = two things
   args = {[special$}
ArgTest $z $y $z $x
=> a = [special$
   b = two things
   args = {[special$}one

The effect of the list structure in args is illustrated by the treatment of variable z in Example 7-2. The value of z has special characters in it. When $z is passed as the value of parameter b, its value comes through to the procedure unchanged. When $z is part of the optional parameters, quoting is automatically added to create a valid Tcl list as the value of args. Example 10-3 on page 127 illustrates a technique that uses eval to undo the effect of the added list structure.


      Previous section   Next section
    Top