dutchlab
dutchlab

Reputation: 590

TCL get value of concatenated variable

x is a list of device names (device-1, device-2, device-3) There is a variable created for each device1 by concatenating the string port so you end up with $device-1port.

looping over x creates

[expr $${x}port-2000 ]   #x is device-1 so it is trying $device-1port-2000 which throws error.

I would like to get the numeric value of $device-1port into a variable without a dash.

set xvar $${x}port

[expr $xvar-2000 ]

or can i wrap the $${x}port in something within the expr statement.

Upvotes: 0

Views: 475

Answers (2)

Donal Fellows
Donal Fellows

Reputation: 137787

One of the nicest ways to work with such complex variables is to use the upvar command to make a local “nice” alias to the variable. In particular, upvar 0 makes a local alias to a local variable; slightly tricky, but a known technique.

upvar 0 ${x}port current_port

Now, we have any read, write or unset of current_port is the same as a read/write/unset of the port with the awkward name, and you can write your code simply:

puts [expr { $current_port - 2000 }]
set current_port 12345
# etc.

The alias will be forgotten at the end of the current procedure.


Of course, you probably ought to consider using arrays instead. They're just simpler and you don't need to work hard with computed variable names:

set x 1
set device($x,port) 12345
puts [expr {$device($x,port) - 2000}]

Upvotes: 0

Anton Kovalenko
Anton Kovalenko

Reputation: 21517

To read a variable with interpolations in its name, use single-argument set:

set withoutadash [set device-${x}port]

Generally, it's better to use arrays for this kind of thing.

Upvotes: 3

Related Questions