TCL lappend 创建另一个层次结构

TCL lappend creates another hierarchy

查看下面的代码:

proc forbid args {
   set dict_name [ lindex $args 1 ]
   puts "dict_name llength is: [llength $dict_name ]"
   set listy [ list "$${dict_name}" ]
   lappend listy [ lindex $args 2 ]
   puts $listy
}
forbid k l m n
exit

代码输出为:

dict_name llength is: 1
{$l} m

为什么不是$l m{$l m}? 谢谢

原因是调用puts时没有将列表转换为字符串。因为你不这样做,所以 Tcl 必须这样做。当 Tcl 将列表转换为字符串时,它会生成一个字符串,可以保证将其转换回列表。它通过在需要某种保护的元素周围添加反斜杠 and/or 大括号来做到这一点。

例如:

% puts [list a b c]
a b c
% puts [list $a $b $c]
{$a} {$b} {$c}

大括号不是数据的一部分,它只是将列表转换为字符串时输出的一部分。您可以(而且通常应该)通过将列表显式转换为字符串来更改格式。

例如,这个:

puts [join $listy " "]

... 将导致:

$l m