0

I'm attempting to create a very simple array in TCL but I can't figure out the syntax to make it append text to a variable in an assignment. Here is what I am trying to do:

set var1 "some text"
set var2 "other text"
array set arrValues { 
    1    $var1 + _text
    2    $var2 + _text
    3    $var1 + _different_text
    4    $var1 + _different_text
}

How do I tell it that it should treat $var1 + _text as the data that needs to get inserted without needing to make another variable outside of the array?

3 Answers 3

1

Since you want to substitute the variables, you can't use {braces} to declare the array elements:

$ tclsh
% set var1 "some text"
some text
% set var2 "other text"
other text
% array set arrValues {1 ${var1}_text 2 ${var2}_text 3 ${var1}_different_text 4 ${var2}_different_text}
% parray arrValues
arrValues(1) = ${var1}_text
arrValues(2) = ${var2}_text
arrValues(3) = ${var1}_different_text
arrValues(4) = ${var2}_different_text
% array set arrValues [list 1 ${var1}_text 2 ${var2}_text 3 ${var1}_different_text 4 ${var2}_different_text]
% parray arrValues
arrValues(1) = some text_text
arrValues(2) = other text_text
arrValues(3) = some text_different_text
arrValues(4) = other text_different_text
Sign up to request clarification or add additional context in comments.

Comments

1

You can just join the string together... But so it knows where the variable name ends, put it in braces ${var1}_text... And so your array values get evaluated, put them in quotes instead of braces, or use [list a b c] (Please excuse lack of format - answering from my phone)

Comments

1

The simplest robust way is probably to use the list command to construct the thing to use with array set:

set var1 "some text"
set var2 "other text"
array set arrValues [list \
    1    "$var1 + _text" \
    2    "$var2 + _text" \
    3    "$var1 + _different_text" \
    4    "$var1 + _different_text"
]

That's assuming that you want just the variable substituted. ("${var1}_text" might be more suitable for your specific case; you can build the value to insert using any Tcl substitutions you want.) However, in this case I'd actually just do this instead:

set var1 "some text"
set var2 "other text"
set arrValues(1) "$var1 + _text"
set arrValues(2) "$var2 + _text"
set arrValues(3) "$var1 + _different_text"
set arrValues(4) "$var1 + _different_text"

It's shorter. The array set command only really becomes useful when you are using literal dictionaries as the source of what to set, or when you're taking a serialized value generated elsewhere entirely (e.g., from an array get in another context).

Comments

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.