Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

nested - in tcl, can't read a variable when its name is comprised of another variable

Basically, what I'm doing is

set i 0

set log_$i "blah blah"

puts $log_$i;                  # expecting to see "blah blah"

this returns the error:

can't read "log_": no such variable

I've tried all different kinds of grouping, nothing seems to work

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

BUT…

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

The upvar command is tricky stuff, and allows for all sorts of really powerful techniques. It also makes the local aliases to variables very efficient (though this alias does not include looking up the variable each time; you'll need to rerun upvar if you want the alias to point to something else).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...