It's certainly not a bad strategy. You just have to be careful to follow it consistently in your implementation. For example, consider the following procedure:
Code:
proc msg {argList} {
puts [lindex $argList 0]
}
Now you have to remember that
msg expects a
list as an argument. So you'll get unexpected results if you accidentally try this:
[tt]%
msg "Hello, world!"
Hello,[/tt]
Instead, you need to do this:
[tt]%
[ignore]msg [list "Hello, world!"][/ignore]
Hello, world![/tt]
There are a couple of other strategies that you might want to consider, though. One is that you can define a procedure to accept optional arguments simply by providing default values to those arguments in your procedure definition. This can be a nice technique for extending existing procedures in a backwards compatible manner. Let's say that we had an existing version of
msg defined like this:
[tt]proc msg {text} {
puts $text
}[/tt]
Now, we'd like to extend
msg to accept a channel identifier argument, so we can send the message somewhere other than [tt]stdout[/tt]. To do so, we'll add a second argument to
msg, but make it optional by providing a default value of "stdout":
[tt]proc msg {text
{fid stdout}} {
puts $text
}[/tt]
You can now call
msg with either 1 or 2 arguments:
[tt]msg "Hello, world!" ;# Send to stdout by default
msg "Hello, world!" stderr ;# Explictly send to stderr[/tt]
Another approach is that you can define a procedure so that it accepts a variable number of arguments. You do so by using the special argument name "args" in the procedure declaration. For example:
Code:
proc sum {args} {
set total 0
foreach val $args {
set total [expr {$total + $val}]
}
return $total
}
This defines
sum as a procedure that accepts 0 or more separate arguments. All of the arguments passed to
sum are stored as a list in the variable
args. If you provide no arguments to
sum, then
args contains an empty list. You can use all standard Tcl list manipulation commands on
args.
You can also define a procedure so that it accepts a minimum number of arguments. Just provide explicit argument names for the required arguments, and then use
args as the last argument. For example:
Code:
proc broadcast {msg args} {
foreach channel $args {
puts $channel $msg
}
}
Now the first argument provided to
broadcast is stored in
msg, and any additional arguments are stored as a list in
args:
[tt]%
broadcast "Hello, world!" stdout stderr
Hello, world!
Hello, world![/tt]
- Ken Jones, President, ken@avia-training.com
Avia Training and Consulting,
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax