Version 17 of cmdline

Updated 2010-08-10 08:37:47 by dkf

Package cmdline is a part of Tcllib. Documentation can be read online at http://tcllib.sourceforge.net/doc/cmdline.html , and examples of cmdline usage appear in ftpd, htmlparse, and pop3.

Glenn Jackman offers [L1 ] and [L2 ] as "examples of cmdline in action". (AMG: 404)

The cmdline package can be used for both programs which accept arguments via the argv list as well as procs which have specific needs for argument processing.


12 Jun 2003: Here is an example of its use (http://groups.google.com/groups?th=89144039acd5554b ):

    package require cmdline

    proc test {args} {
        set options {
            {first.arg  1 "1st arg"}
            {second.arg 2 "2nd arg"}
            {third.arg  3 "3rd arg"}
            {fourth.arg 4 "4th arg"}
        }
         
        # cmdline::getoptions will throw an error for unknown option
        array set params [::cmdline::getoptions args $options]

        # do other stuff...
        parray params
    }                
     
    test -fourth last -first one

Here's a portion of another example, this one by Eric Varsanyi:

 proc sc_dump {args} {
        set ::argv0 "sc_dump"
        array set arg [::cmdline::getoptions args {
                {v "Verbose"}
                {t "Only dump top 10 LRU"}
                {hit "Sort by hit count"}
                {top.arg end "Dump top N LRU"}
                {main "Dump main cache"}
                {unrunnable "Dump unrunnable cache"}
                {i "Case insensitive expression match"}
                {all "Search entire entry (otherwise SQL only)"}
        }]
        if {$arg(t)} {
                set arg(top) 10
        }

        # Pick cache groups to dump
        set clist {}
        if {$arg(main)} {
                lappend clist main
        }
        if {$arg(unrunnable)} {
                lappend clist unrunnable
        }
        if {[llength $clist] == 0} {
                set clist {main unrunnable}
        }
        ...

cmdline::getoptions args $optlist has a nasty side effect: it removes all of the elements from args.

So, if you want to do anything with the original args after calling getoptions, save args or do it before calling getoptions.

HaO This is by design. If there are any non-flag options, they are left in args. The special flag -- may be used to signal end of flags to.

Example Code:

proc printdata args {
        dict set dParams {*}[::cmdline::getoptions args {\
                        {page.arg                0        "current page"}
                        {pages.arg                0        "number of pages"}
                        } "printdata ?options? Data"]
        if {1 != [llength $args]} {
                return -code error "No data given"
        }
        set data [lindex $args 0]
}

which might be called with:

printdata -page 1 -pages 2 -- "--Head data to print--"