Should 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.
[ZC] append $aa string
[ZC] append是将aa看成字符串,哪怕其本身是个list,append将要添加的string直接添加在aa的尾部,没有任何空格分隔, 比如aa = [list 11 22 33], string = 44, 那么结果是11 22 3344
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.
[ZC] lappend $aa element
[ZC]lappend只对list aa添加一个元素,换言之,不管element里面是什么数据结构,最终element会被看成整体添加到aa中,比如aa = [list 11 22 33], element = [44 55 66], 那么结果是11 22 33 {44 55 66}, 一共4个元素
contact (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!
[ZC] contact $aa $list
[ZC]contact 会将 list认为是一个列表,其会将list中的元素一个一个添加到原列表aa中,新列表是两个列表的总和。应该善用contact这个命令
Example - source codeset 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