02.03.2014 Views

Tornado

Tornado

Tornado

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

B<br />

Tcl<br />

B.2.7 Procedures<br />

Procedure definition in Tcl is straightforward, and resembles many other<br />

languages. The command proc builds a procedure from its arguments, which give<br />

the procedure name, a list of its arguments, and a sequence of statements for the<br />

procedure body. In the body, the return command specifies the result of the<br />

procedure. For example, the following defines a procedure to compute the square<br />

of a number:<br />

B<br />

proc square {i} {<br />

return [expr $i * $i]<br />

}<br />

If a procedure’s argument list ends with the word args, the result is a procedure<br />

that can be called with any number of arguments. All trailing arguments are<br />

captured in a list $args. For example, the following procedure calculates the sum<br />

of all its arguments:<br />

proc sum {args} {<br />

set accum 0<br />

foreach item $args {<br />

incr accum $item<br />

}<br />

return $accum<br />

}<br />

Defined Tcl procedures are called by name, and can be used just like any other Tcl<br />

command. The following examples illustrate some possibilities:<br />

Table B-8<br />

Calling a Tcl Procedure<br />

Tcl Expression<br />

Result<br />

square 4 16<br />

square [sum 1 2 3] 36<br />

set x "squ"<br />

set y "are"<br />

squ<br />

are<br />

$x$y 4 16<br />

The technique illustrated by the last example—constructing a procedure name “on<br />

the fly”—is used extensively by <strong>Tornado</strong> tools to group a set of related procedures.<br />

The effect is similar to what can be achieved with function pointers in C.<br />

323

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!