1
votes

I have set 3 global variables as below in a file FILE1:

set VAR1    2   
set VAR2    3   
set VAR3    4

Now I want to use these 3 variables in another file FILE2 in iterative way:

Means, something like this:

for {set a 1} {$a < 4} {incr a} {
    $::VAR$a
}

where VAR$a - should be incremented each time to VAR1,VAR2,VAR3 etc...

But if I try like this using the global variable I get error in tcl

Any better solution for this?

1
This is exactly the kind of thing arrays are for.Scott Hunter

1 Answers

2
votes

Either make your meaning clearer to the interpreter

set ::VAR$a

(you are aware that this is just getting the variable's value without doing anything with the value, that is, a pointless operation, right?)

Or use an array, which is basically a two-part variable name:

set ::VAR($a)

in which case you need to initialize as an array:

set VAR(1) 2

etc, or

array set VAR {1 2 2 3 3 4}

The reason why $::VAR$a doesn't always work is AFAICT that the variable substitution becomes ambiguous. Given these definitions:

set foobar 1
set a foo
set b bar

what should $a$b substitute into? To avoid ambiguity, the substitution rules are kept simple: the first substitution stops before the second dollar sign, and the whole expression evaluates to the string foobar. How about $$a$b to substitute the value of foobar, then? No, a dollar-sign followed directly by a character that can't be a part of a variable name means that the first dollar sign becomes just a dollar sign: you get $foobar. The best way to handle this is to reduce the levels of substitution using the set command to get a value: set $a$b. Bottom line: variable substitution using $ does not always work well, but the set always does the job.

Documentation: set, Summary of Tcl language syntax