In tcl it cannot read a variable when its name consists of another variable

Basically i do

set i 0

set log_$i "blah blah"

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

this returns an error:

can't read "log_": no such variable

I tried all kinds of groupings, nothing works

+3
source share
3 answers

The problem is that $-substitution stops when it occurs $(and many other punctuation marks).

To do what you do, do this to read the variable (using a form with one command argument set):

puts [set log_$i]

This compiles exactly in the form of bytecode that you expect.

But...

Do not do this if you can avoid it.

, , , , :

set i 0
set log($i) "blah blah"
puts $log($i)

. , , ( ) :

set i 0
upvar 0 log_$i v
set v "blah blah"
puts $v

upvar - . ( , upvar, , - ).

+11

:

== > tclsh

% set i 0

0

% set log[set i] bb

bb

% puts "[set log[set i]]"

bb
0

Differently:

% set i 0
0
% set log(0) "blah blah"
blah blah
% puts $log($i)
blah blah
0
source

Source: https://habr.com/ru/post/1779969/


All Articles