tcl

In TCL::cmdline or related package, is it possible to specify an option that may be set multiple times?


For example, in python::click, I might declare an option:

@click.option('--foo', nargs=-1)

And the user may specify the arg over and over again:

python3 -m mypkg --foo bar --foo biz

Or in BASH:

declare -a a_arr;

while getopts 'a:' opt; do
  case $opt in:
    a) a_arr+=($OPTARG);;
  esac
done
shift (($OPTIND - 1))


But in TCL, to parse the cmdline, I see I must run:

array set params [::cmdline::getoptions argv $options $usage]

This doesn't have the surface area of BASH, where I can make it work anyway, and I'm not seeing the documentation indicating there is an nargs option available that'll pack an array in the params array.

But I imagine there is some way to have an argument repeated multiple times.


Solution

  • Shawn is right, but you need to alter the options argument a bit:

    An example:

    package req cmdline
    
    set options {
        {a          "set the atime only"}
        {m          "set the mtime only"}
        {c          "do not create non-existent files"}
        {r.arg  ""  "use time from ref_file"}
        {t.arg  -1  "use specified time"}
    }
    set opts [lmap opt $options {lindex $opt 0}]
    
    set argv {-a -t 1234 -t 4567}
    set params [dict create]
    
    while {[set status [cmdline::getopt argv $opts opt arg]]} {
        # TODO handle errors, when $status == -1
        dict lappend params $opt $arg
    }
    
    puts $params       # => a 1 t {1234 4567}