Reputation: 191
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?
Upvotes: 0
Views: 89
Reputation: 137577
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).
Upvotes: 1
Reputation: 246807
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
Upvotes: 1
Reputation: 2218
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)
Upvotes: 1