EdouardDKP
EdouardDKP

Reputation: 71

TCL Get the value of a second level variable

I à stuck with a TCL issue. I would like to have access to the content of a second level variable with keeping the format (list). please see my code : At first, I declare variable contents

set x1y {1 2 3 4}
set x2y {10 11 12 13}

After I perform a for loop

for { i 0} {i < 4} { incr i}

I would like to have in xy variable the content of x1y with keeping the list format

 set xy [eval ["x${i}y"]]
 foreach x $xy {
  ....
 }

Do you have any idea / proposal. I tried subst but it doesn’t keep the format. Thank you in advance

Upvotes: 0

Views: 178

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137567

The way to read from a variable whose name is not a constant is to use the single argument form of set:

set x1y {1 2 3 4}
set x2y {10 11 12 13}

foreach i {1 2} {
    foreach val [set x${i}y] {
        puts "$i --> $val"
    }
}

However, it is usually easier to make an alias to the variable with upvar 0, like this:

foreach i {1 2} {
    upvar 0 x${i}y xy
    foreach val $xy {
        puts "$i --> $val"
    }
}

And in almost every case where you're doing this, you should consider using arrays instead (remembering that Tcl's arrays are associative arrays; you can use compound keys as well as simple integers):

set xy(1) {1 2 3 4}
set xy(2) {10 11 12 13}

foreach i {1 2} {
    foreach val $xy($i) {
        puts "$i --> $val"
    }
}

You probably want to try to avoid using eval or subst for this sort of thing; those commands have side effects that may hurt the stability of your code if you're not careful. Definitely not ones for cases like these. (Also, they'll be slower as they force Tcl to recompile its internal bytecode more frequently. All the solutions I present above don't have that misfeature.)

Upvotes: 1

Dinesh
Dinesh

Reputation: 16428

set x1y {1 2 3 4}
set x2y {10 11 12 13}
for {set i 1} {$i <= 2} {incr i} {
     foreach e [set x${i}y] {
            puts $e
     }
}

Upvotes: 0

Related Questions