Version 4 of getopt

Updated 2006-12-11 09:15:51 by suchenwi

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.


wdb In my case, I use switches always with a value such that there is always a pair key - value which I collect into an array as follows:

 % proc testSwitch {arg1 args} {
        array set switch [concat {
                -accept no
        } $args]
        list arg1 was $arg1, -accept was $switch(-accept).
 }
 % testSwitch Wurst
 arg1 was Wurst, -accept was no.
 % testSwitch Kaese -accept yes
 arg1 was Kaese, -accept was yes.
 %

RS: true, named arguments can be handled simpler. What I wanted was an option extractor from command lines, which may contain different numbers of file names, etc.


Category Example