What is the recommended way of concatenation of strings?
Asked
Active
Viewed 7.3k times
23
-
Look also answers at https://stackoverflow.com/questions/1430093/how-to-concisely-concatenate-strings-in-tcl – B. Go Jun 19 '19 at 22:52
3 Answers
42
Tcl does concatenation of strings as a fundamental operation; there's not really even syntax for it because you just write the strings next to each other (or the variable substitutions that produce them).
set combined $a$b
If you're doing concatenation of a variable's contents with a literal string, it can be helpful to put braces around the variable name or the whole thing in double quotes. Or both:
set combined "$a${b}c d"
Finally, if you're adding a string onto the end of a variable, use the append
command; it's faster because it uses an intelligent memory management pattern behind the scenes.
append combined $e $f $g
# Which is the same as this:
set combined "$combined$e$f$g"
![](../../users/profiles/301832.webp)
Donal Fellows
- 120,022
- 18
- 134
- 199
-
1Note that the first argument to `append` is a variable name, just like the first arg to `set`. – Donal Fellows May 07 '11 at 06:25
8
If they are contained in variables, you can simply write "$a$b"
.
![](../../users/profiles/151238.webp)
LaC
- 12,088
- 5
- 34
- 38
-
I am doing exactly in the way you have written with a small difference like ${a}${b}, but I worry that it is not a correct way to do, is it? – Narek May 06 '11 at 08:30
-
2They are both right - you would use the ${a}${b} construction in the case where you are building a string and there may be an ambiguity about the variable name e.g. set url /admin/item-edit?item_name=${item_id}name – TrojanName May 06 '11 at 08:42