Cmdline包主要用来处理命令行输入。
例子1:
#!/usr/local/bin/tclsh
package require cmdline
set flag_a 0
set flag_b 0
set value_r 0
set value_t ""
set usage "Usage:
-a set flag a
-b set flag b
-r value set flag r
-t value set flag t"
while {[set ok [cmdline::getopt argv {a b r.arg t.arg} opt val]] > 0} {
switch -exact -- $opt {
a {set flag_a 1}
b {set flag_b 1}
r {set value_r $val}
t {set value_t $val}
}
}
if { $flag_a == 1 } {
puts "===Option a is set!==="
}
if { $flag_b == 1 } {
puts "===Option b is set!==="
}
if { $value_r != 0 } {
puts "===Option r is set, the value is $value_r==="
}
if { $value_t != "" } {
puts "===Option t is set, the value is $value_t==="
}
if { $flag_a == 0 && $flag_b == 0 && $value_r == 0 && $value_t == "" } {
puts stderr $usage
}
例子2:
#!/usr/local/bin/tclsh
package require cmdline
set options {
{a "This is option a!"}
{b "This is option b!"}
{r.arg "" "This is option r, it should be r value"}
{t.arg -1 "This is option t, the default value is -1"}
}
set err_msg "Usage:
-a This is option a
-b This is option b
-r value This is option r, it should be r value
-t valua This is option t, the default value is -1"
array set params [cmdline::getoptions argv $options $err_msg]
set flag 0
if { $params(a) } {
puts "===The option a is set=="
set flag 1
}
if { $params(b) } {
puts "===The option b is set=="
set flag 1
}
set has_t [expr {$params(t) != -1}]
if { $has_t } {
puts "===The option t is set==="
puts "===$params(t)==="
set flag 1
}
set has_r [expr {[string length $params(r)] > 0}]
if { $has_r } {
puts "===The option r is set==="
puts "===$params(r)==="
set flag 1
}
if { $flag == 0 } {
puts stderr $err_msg
}