在tcl中,当变量名称由另一个变量组成时,无法读取该变量 [英] in tcl, can't read a variable when its name is comprised of another variable
问题描述
基本上,我在做什么
set i 0
set log_$i "blah blah"
puts $log_$i; # expecting to see "blah blah"
这将返回错误:
无法读取"log_":没有这样的变量
can't read "log_": no such variable
我尝试了所有不同的分组方式,但似乎没有任何作用
I've tried all different kinds of grouping, nothing seems to work
推荐答案
您遇到的问题是,当$
-替换遇到$
(以及许多其他标点符号)时,它也会停止.
The issue you've got is that $
-substitution stops when it encounters a $
(and lots of other punctuation too).
To make what you're doing work, you'd do this to read the variable (using the single-argument form of the set
command):
puts [set log_$i]
这完全可以编译为您期望的字节码.
That compiles to exactly the sort of bytecode that you'd expect.
如果可以避免的话,不要那样做.
Don't do it that way if you can avoid it.
每当您考虑构造这样的变量时,您就更有可能需要使用数组:
Any time you're thinking about constructing variables like that, you're more likely to be in need of using arrays:
set i 0
set log($i) "blah blah"
puts $log($i)
确实有效.而且,如果您确实需要使用名称已被构造的变量,则像这样为它构造一个(通常是本地的)变量别名通常会更容易:
That does work. And if you're really in need of working with a variable whose name is constructed, it's often easier to construct a (typically local) variable alias to it like this:
set i 0
upvar 0 log_$i v
set v "blah blah"
puts $v
upvar
命令非常棘手,并且可以进行各种真正强大的技术.它还使变量的局部别名非常有效(尽管该别名并不每次都包含查找变量;如果希望别名指向其他内容,则需要重新运行upvar
.)
这篇关于在tcl中,当变量名称由另一个变量组成时,无法读取该变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!