Tcl - append v lappend v concat
Archive - Originally posted on "The Horse's Mouth" - 2007-10-23 06:03:52 - Graham EllisShould you use append, lappend or even concat to add to variable in Tcl?
append puts one string directly on the end of another, without adding any extra characters beyond those in the incoming variables.
lappend treats the target string as a list, and will usually add an extra space on the end of it prior to appending the new item so that the result is also a list with ONE new item added ... the added item being protected using additional characters such as { and } to turn it into a list element if necessary.
concat (and note the different syntax!) takes two LISTS and joins them together - it differs from lappend in that lappend takes the second element as a single item and not as a list. Concat is something that many occasional Tcl users seem to forget about ... and then waste time writing a loop of lappends!
Example - source code
set people "John Joan Jane"
set gatecrashers "Bill Ben Boris"
#
# append adds to string, lappend adds to list
puts $people
append people t
lappend people Julian
puts $people
#
# concat connects two lists, lappend adds one item to a list
set everyone [concat $people $gatecrashers]
puts $everyone
lappend people $gatecrashers
puts $people
In operation:
Dorothy:~/csr1 grahamellis$ tclsh alc
John Joan Jane
((append will add "t" to Jane, lappend adds new item Julian))
John Joan Janet Julian
((concat adds a whole new list))
John Joan Janet Julian Bill Ben Boris
((but lappend adds a single item to the list))
John Joan Janet Julian {Bill Ben Boris}
Dorothy:~/csr1 grahamellis$