如何在 Tcl 中创建动态变量名

How to create a dynamic variable name in Tcl

我有一个超级列表,例如:

set superlist {{1 2 3} {4 5 6} {7 8 9} {10 11 12} ...}

但是我事先并不知道我在超级列表中会有多少个子列表。无论如何创建子列表,例如:

list1 {1 2 3}
list2 {4 5 6}
list3 {7 8 9}
...

我想我必须根据超级列表中子列表的数量来创建变量列表名称。谁能帮我解决这个问题,即如何在执行代码时创建变量名?

可以这样做:

foreach sublist $superlist {
    set list[incr index] $sublist
}

但是不要!

实际上,数组.

你几乎肯定会更快乐
foreach sublist $superlist {
    set list([incr index]) $sublist
}

原因是使用变量索引访问的语法:

for {set index 1} {$index <= 3} {incr index} {
    puts "at $index is the list $list($index)"
}

如果你用另一种方式来做,你必须使用一些更笨拙的东西,比如 single-argument set.

for {set index 1} {$index <= 3} {incr index} {
    puts "at $index is the list [set list$index]"
}

(顺便说一句,这是从 variable-named 变量中读取数据的最佳方式。)