Reputation: 1849
I have 5 arrays and i want to iterate over them one by one, so I'm thinking to add these arrays to another array and access them one by one with indexes
array set ListOfArrays {1 $array1 2 $array2 3 $array3 4 $array4 5 $array5}
for { set i 1} { $i <= 5 } {incr i} {
set list $ListOfArrays($i)
foreach {key} [array names list] {
puts $key
}
}
The output is empty...
what is wrong?!
Upvotes: 0
Views: 1074
Reputation: 13252
As an alternative to the array
-based solutions, a solution using dictionaries. I borrow the data from Jerry's answer.
set dict1 {1 a 2 b}
set dict2 {3 c 4 d}
set dict3 {5 e 6 f}
set dict4 {7 g 8 h}
set dict5 {9 i 10 j}
set dicts [list $dict1 $dict2 $dict3 $dict4 $dict5]
foreach dict $dicts {
foreach key [dict keys $dict] {
puts $key
}
}
Unlike arrays, dictionaries can be passed as values and evaluated using $
. This means that you can put your five dictionaries in a list and traverse that list with foreach
. In the inner loop, each key is printed.
foreach dict $dicts {
dict for {key -} $dict {
puts $key
}
}
is basically the same thing.
Documentation: dict, foreach, list, puts, set
Upvotes: 0
Reputation: 137557
Tcl's arrays can't be put in a list; they're (collections of) variables, not values. But you can put the names of the arrays in.
array set ListOfArrays {1 array1 2 array2 3 array3 4 array4 5 array5}
for { set i 1} { $i <= 5 } {incr i} {
upvar 0 $ListOfArrays($i) list
foreach {key} [array names list] {
puts $key
}
}
The upvar 0
? It makes a local alias to a variable, and it's great for this sort of thing.
Upvotes: 1