在 tcl 中,当变量名称由另一个变量组成时,无法读取该变量 [英] in tcl, can't read a variable when its name is comprised of another variable

查看:39
本文介绍了在 tcl 中,当变量名称由另一个变量组成时,无法读取该变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我正在做的是

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

推荐答案

您遇到的问题是 $-substitution 在遇到 $(和还有很多其他标点符号).

The issue you've got is that $-substitution stops when it encounters a $ (and lots of other punctuation too).

为了使您正在做的事情工作,您将这样做以读取变量(使用 set 命令):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆