Tcl append Command
last modified October 20, 2026
The Tcl append command concatenates strings to a variable. It's more
efficient than using set for string concatenation. The command
modifies the variable in place.
Basic Definition
The append command appends one or more values to a variable. If the
variable doesn't exist, it creates it. The command returns the new value.
Syntax: append varName ?value value ...?. The first argument is the
variable name. Subsequent arguments are values to append.
Basic String Concatenation
This shows the simplest usage of append to concatenate strings.
set str "Hello" append str " " "World" puts $str
This creates a variable str with value "Hello", then appends a space
and "World". The result is "Hello World" printed to standard output.
Appending Multiple Values
The append command can append multiple values in a single call.
set sentence "Tcl" append sentence " is" " a" " powerful" " language" puts $sentence
Here we build a sentence by appending multiple words in one command. This is
shorter than several separate append calls and avoids repeated
command overhead.
Appending to Non-existent Variables
append creates the variable if it doesn't exist, unlike some other
commands.
# No prior definition of 'text' append text "Creating" " new" " variable" puts $text
This demonstrates that append will create the text
variable automatically. The variable is initialized with the concatenated values.
Appending Numbers
append works with numbers by converting them to strings.
set result "The answer is: " append result 4 2 puts $result
Numbers 4 and 2 are converted to strings and appended. The result is "The answer is: 42". Note this is string concatenation, not arithmetic addition.
Appending in Loops
append is often used in loops to build strings incrementally.
set output ""
foreach word {Tcl is great for scripting} {
append output $word " "
}
puts [string trim $output]
This loop builds a sentence by appending each word with a space. The final
string trim removes the trailing space. This pattern is common for
building output strings.
Appending to List Elements
The append command works on variables, not on list elements, so
changing one element of a list takes a few steps with lindex and
lset.
set colors {red green blue}
set second [lindex $colors 1]
append second "ish"
lset colors 1 $second
puts $colors
The second element (index 1) is copied into the second variable,
"ish" is appended to it, and lset stores the result back in the
list. The list becomes "red greenish blue".
Best Practices
- Performance: Use
appendinstead ofsetfor concatenation. - Clarity: Split very long argument lists into several appends.
- Whitespace: Remember to include spaces between words.
- Lists: For complex data, consider using lists instead.
- Initialization: Initialize variables for clarity when needed.
This tutorial covered the Tcl append command with practical
examples showing its usage in different scenarios.
Author
List all Tcl Tutorials.