The format for defining a Tcl proc is simply:
proc name {var1 var2.. varn} { }
There is a special keyword when defining the variable list, args. When placed at the end of proceedures argument list, it results all other values being passed as a single list. In effect then, it allows a Tcl proc to recieve a variable number of arguments.
So, the above definition could be re-written as:
proc name {args} { }
The implication here is that keeping to a single string as an even numbered list tags and values, it becomes possible to define variables within the calling procedure. Once passed, these can be set using the standard Tcl foreach command.
proc name {args} {
foreach {*}$args {break}
}
Now, this process can be taken one step further. Many system commands have values, commands and switches and it can be helpful to emulate these patterns within a Tcl script as it saves the mind power of having to switch between programming styles.
The next step then is:
proc name {val1 val2 args} {
foreach {*}$args {break}
}
Where val1 and val2 can be subcommands, required values and arguments or optional values in the form of switches.
If option tags with leading '-' are used be used these will have detrimental effect to creating legal variable names but they can be removed quite easily using one two ways using regsub or a string Tcl commands in combination with foreach. i.e.,
foreach {a b} $args { regsub -line {\-} $a {} a ; set $a $b }
Or,
foreach {a b} $args { set [string range $a 1 end] $b }
Comments