In using a Tcl script as a command line call, being able to parse the argument passed to the script is vital. The following snippet shows how to retrieve and assign such values.
line 2
line 3
# list of tested optionsThe following line will result in an error as no value passed for option -e. The list element -5 will not be mistaken for an option as it is not a member of the valid options list.
set opts "-a -b -c -d -e"
##
# parse a string of arguments
##
# arguments:
# opts - list of options not in dict format
# args - list of options-values to be parsed
# returns:
# tagged list of option/values pairs as dict
#
proc parse {opts args} {
set i 0
foreach item $args {
if { $item in $opts } {
set tmp [string trim $item -]
incr i
} else {
lappend opt($tmp) $item
}
}
if { $i != [array size opt] } {
error -errorinfo "Error: unbalanced list in arguments."
}
return [array get opt]
}
parse $opts -a {1 2 3} -b a b c -c 4 -3 -d -5 -e
In the above example option -a receives a braced list, that is its contents is a single member of a list. The following line is balanced:
parse $opts -a {1 2 3} -b a b c -c 4 -3 -d -5 -e f
After stripping initial dashes, the following tagged list is returned
d -5 e f a {{1 2 3}} b {a b c} c {4 -3}
The unsorted ordering being the result of maintaining values in the parse procedure as an array, In practice, this will have no impact of the application of the code.
No comments:
Post a Comment