1

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?

2 Answers 2

5

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

set foo [set [lindex $bar 0]_someString]
Sign up to request clarification or add additional context in comments.

2 Comments

The double quotes aren't necessary; Tcl doesn't get confused by such things.
Ah.. yes. I blame it on too much bash programming :-). Edited my answer - thanks.
-1

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

2 Comments

Edited my questions, I want the value in bar0_someString varialbe, not the variable name.
This is an antipattern, one of the few things we really recommend not doing in Tcl. Use @slebetman's answer instead, which is both much faster and safer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.