如何将命令行参数存储在数组中

How to store a command line arguments in an array

如何在 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)"