Richard Suchenwirth 2006-12-08 - Tcl scripts started from the command line can often be configured with switches (also called flags) like
$ myscript.tcl -v -sep ';' whatever
Here's my little take to parse out switches from the command line (argv) by name. If a variable name is given, the word following the switch is assigned to it; in any case, the flag (and possibly the consumed following word) are removed from the command line, and 1 is returned if the flag was found, else 0.
proc getopt {_argv name {_var ""}} { upvar 1 $_argv argv set pos [lsearch -regexp $argv ^$name] if {$pos>=0} { set to $pos if {$_var ne ""} { upvar 1 $_var var set var [lindex $argv [incr to]] } set argv [lreplace $argv $pos $to] return 1 } else {return 0} }
Usage examples:
set sep ";" ;# set default first getopt argv -sep sep ;# possibly override with user preference set verbose [getopt argv -v] ;# boolean flag, no trailing word
Searching with -regexp allows to specify longer mnemonic names, so it still succeeds on longer flags, e.g.
$ myscript.tcl -separator '\t' ...
If you use this separator for joining lists, make sure to subst -nocommand it before use.