如何将命令行参数存储在tcl中的数组中?
我试图将命令行参数(argv)存储在数组中。argv是不是数组?我尝试了下面的代码,但不适合我。
proc auto args {
global argv
set ifname [lindex $argv 0]
puts "***********$ifname"
puts "$argv(2)"
for { set index 1} { $index < [array size argv ] } { incr index } {
puts "argv($index) : $argv($index)"
}
}
#Calling Script with arguments
auto {*}$argv
Tcl的argv
全局是一个列表,而不是数组,因为顺序很重要,列表是处理参数的完全合理的方式。这就是为什么要对它使用lindex
(和其他列表操作)。您可以将其转换为数组,但大多数代码最终会对此感到"惊讶"。因此,最好使用不同的数组名称(下面的"arguments
"):
proc argumentsToArray {} {
global argv arguments
set idx 0
unset -nocomplain arguments; # Just in case there was a defined variable before
array set arguments {}; # Just in case there are no arguments at all
foreach arg $argv {
set arguments($idx) $arg
incr idx
}
}
argumentsToArray
puts "First argument was $argument(0) and second was $argument(1)"