如何替换数组名称中的变量?

hey*_*hey 0 arrays tcl

我们假设filevalue_ $ thefile是一个包含列表的数组

foreach element [array names thefilevalue_$thefile] {
    puts "[lindex $thefilevalue_[subst $thefile]($element) 0]"
}
Run Code Online (Sandbox Code Playgroud)

但它返回:

can't read "thefilevalue_": no such variable

我在tcl 8.4,我不能升级它.

我该怎么办呢?

谢谢

And*_*ong 6

使用set和转义括号,例如

array set thefilevalue_test {reds {orange red purple} blues {green blue purple}}
set thefile test
foreach element [array names thefilevalue_$thefile] {
    puts [lindex [set thefilevalue_$thefile\($element\)] 0]
}
Run Code Online (Sandbox Code Playgroud)

这为我输出(Tcl 8.0.5,我也无法升级):

orange
green
Run Code Online (Sandbox Code Playgroud)

  • 考虑使用`upvar 0 thefilevalue_ $ thefile ary`为该数组提供一个较短的名称.它使代码的其余部分更容易编写(例如,`$ ary($ element)`而不是那些带`set`的体操. (4认同)
  • 此外,在这种情况下,你可以做`foreach {element content} [array getfilevalue_ $ thefile] {...}` (3认同)