Stan
Stan

Reputation: 38255

Tcl set variable by concatenate a command and string

I am trying to set a variable like this

puts [lindex $bar 0]  # prints bar0
set foo $[lindex $bar 0]_someString

But printing the foo variable not getting the value in foo:

puts $foo  # prints $bar0_someString
# but I want the value in bar0_someString varialbe
# not the variable name.

Is this a syntax error? Is it a bad coding style to declare a variable? Is there a better way to do this?

Upvotes: 1

Views: 654

Answers (2)

slebetman
slebetman

Reputation: 113876

Remember that $x is just a shortcut for set x. So you can also do this:

set foo [set [lindex $bar 0]_someString]

Upvotes: 5

timrau
timrau

Reputation: 23058

The correct syntax should be:

set foo [expr $[lindex $bar 0]_someString]

A running example:

% set bar {a b c}
a b c
% set a_someString tttttt
tttttt
% set foo [expr $[lindex $bar 0]_someString]
tttttt
% puts $foo
tttttt

Upvotes: -1

Related Questions