Why another parsing-routine? Because the other ones like cmdline or OptProc are a little overweighted or just too complex. Here in the wiki, I found links to various usefull parsing-routines, but still I decieded to write one of my own; here is the result. The input is checked/processed against a template, and the result is given back as a list suitable for array set. Switchnames may be shortened. At the bottom of the page later I will add some examples of how a commandline and the corresponding templates can look like.


 # Simple ParameterParsing (SPar)
 # 08.03.2005

 proc spar {tpl cmd} {
      if {[catch {array set a $tpl}]} {
         return -code error {invalid template}; # we could'nt handle this error
      }; # don't stop with other errors - give pgmr the chance to decide later
      set needmore {}
      set count    0
      set seeopts  1
      foreach item $cmd {
              if {[string equal $item "--"]} {
                 set seeopts 0; # end of -flag-processing
              } elseif {[string length $needmore]} {
                 set a($needmore) $item
                 set needmore {}
              } elseif {$seeopts == 1 && [string range $item 0 0] == "-"} {
                 set matches [array names a -glob $item*]; # allows shortening
                 if {[llength $matches]} {
                    set match [lindex [lsort $matches] 0]
                    if {[string index $match end] == ":"} {
                       set needmore $match; # -f: means: 'value follows'
                    } else {
                       set a($match) 1; # otherwise simply return 'true'
                    }
                 } else {
                    lappend a(swiunknown) $item
                 }
              } else {
                 incr count; # each arg counts, even if there are too much
                 if {[info exists a($count)]} {
                    set a($count) $item
                    set a(argcount) $count
                 } else {
                    lappend a(argsuper) $item
                 }
              }
      }
      if {[string length $needmore]} {
         set a(swinovalue) $needmore; # missing value after -switch: at the very end
      }
      return [array get a]; # double conversion is the price for using arrays
 }

 # Tests
 set tpl [list -f1 0 -f2 0 -f3: "*" -f4 0 -test 0 1 "" 2 "" 3 "Default3" -? 0]
 puts "Template: $tpl\n"
 puts Commandline:
 gets stdin cmd
 if {![catch {array set a [spar $tpl $cmd]} rc]} {
    puts "Resultarray:\n"
    parray a
 } else {
    puts $rc
 }

(Examples will be added later)


Category Argument Parsing