TCL list and foreach problem
Say I have a TCL list:
set myList {}
lappend myList [list a b 1]
lappend myList [list c d 2]
.....
Now I want to modify the list like this:
foreach item $myList {
lappend item "new"
}
But at the end I have not modified 开发者_如何学Golist. Why? item is a reference on the list item no?
item
is not a reference to the list item. It is a copy. To do what you want, you could do this:
set newlist {}
foreach item $myList {
lappend item "new"
lappend newlist $item
}
set mylist $newlist
To edit the list “in place”, you can do this:
set idx -1
foreach item $myList {
lappend item "new"
lset myList [incr idx] $item
}
You can also do this if you've got Tcl 8.6 (notice that I'm not actually using $item
; it's just convenient looping):
set idx -1
foreach item $myList {
lset myList [incr idx] end+1 "new"
}
But it won't work on 8.5, where lset
will only replace existing items (and sublists).
for {set i 0} {$i < [llength $myList]} {incr i} {
set item [lindex $myList $i]
lappend item new
set myList [lreplace $myList $i $i $item]
}
If your list is very large, some efficiencies can be made (e.g. the K combinator). They would just add complexity here.
foreach item $myList {
lappend item "new"
}
What you're doing here, is getting a variable (called item), and modifying it to also contain 'new'. basically, you get lists that look like {a new}
, {b new}
and so on. But you leak those variables at the end of each iteration.
What do you really want your list to look like when you're done?
精彩评论