Reputation: 299
I'm new to Tcl. I want to use element-value in a list as the key to another list. So if I have:
set mainlist { list1 list2 }
set list1 { val1 val2 }
set list1 { val3 val4 }
I would like to iterate on mainlist members to get list1 and list2 members.
I tried following but it did't work:
for {set i 0} {$i < [llength $list1]} {incr i} {
set mem [lindex $list1 $i]
for {set j 0} {$j < [llength $mem]} {incr j} {
puts [lindex $mem $j]
}
}
Any solution?
Upvotes: 1
Views: 251
Reputation: 15163
Well, indirect variable access. Use set
for this.
your code could be:
set mainlist { list1 list2 }
set list1 { val1 val2 }
set list2 { val3 val4 }
foreach mem $mainlist {
foreach val [set $mem] {
puts $val
}
}
Why don't you use nested lists?
Edit:
You use $mem
, which has the value list1
or list2
respective. But you try to access the content of the variable list1
, so you have to use set varname
or set $variable_with__varname
.
foreach
is not only quicker, it is also more clear what intention you have.
See the tcl.tk wiki for more information.
Upvotes: 2
Reputation: 71538
I'm not too sure either about what you're asking, but from the loops you did, it seems like you want to do something like this:
set list1 {key1 value1}
set list2 {key2 value2}
set mainlist [list $list1 $list2]
Note that you need to have the variables set before you put them in a list.
Now, if you have the key key2
, to get the value value2
, you can use the loops you did, made a bit differently:
set key "key2"
foreach i $mainlist {
if {[lindex $i 0] == $key} {
puts [lindex $i 1]
}
}
Upvotes: 1
Reputation: 151
I think there is no need of using "for" command. You can use following,
set mainlist { list1 list2 }
set list1_mem [lindex $mainlist 0]
foreach val1 $list1_mem {
puts $val1
}
set list2_mem [lindex $mainlist 1]
foreach val2 $list2_mem {
puts $val2
}
I am using the TCL 8.4 there more optimised ways in after versions.
Upvotes: 0