Home > Back-end >  wants to set a variable with another variable in it using Tcl
wants to set a variable with another variable in it using Tcl

Time:09-23

i want to execute this code but it is not waorking , the tcl script is as follows:

set i 0
foreach pattern { tiger cat horse dog} {
set pat$i abc
puts "pat$i=${pat$i}"
set i [expr {$i   1}]
}

the desired result i want in every loop is :

pat0=abc
pat1=abc
pat2=abc
pat3=abc

Please help me to find my mistake

CodePudding user response:

You can read a variable with a computed name with the one-argument form of set:

set i 0
foreach pattern { tiger cat horse dog} {
    set pat$i abc
    puts "pat$i=[set pat$i]"
    set i [expr {$i   1}]
}

The $... syntax can be considered shorthand for that (except with different, more limited parsing rules that make it more convenient to write).

Alternatively, you can use upvar 0 to make a variable alias with a simple name:

set i 0
foreach pattern { tiger cat horse dog} {
    upvar 0 pat$i p

    set p abc
    puts "pat$i=$p"
    set i [expr {$i   1}]
}

That is much more favoured in a procedure.

HOWEVER, are you sure you need the variable to be called that? Can you use an associative array instead? That's often just as convenient.

set i 0
foreach pattern { tiger cat horse dog} {
    set pat($i) abc
    puts "pat$i=$pat($i)"
    incr i;                      # The incr command is *right there*
}
  • Related