Table of Contents
Often you will want to loop through the contents of an
associative array - without having to specify the elements
explicitly. For this the array names
and array get commands are very
useful. With both you can give a (glob-style) pattern to select
what elements you need:
foreach name [array names mydata] {
puts "Data on \"$name\": $mydata($name)"
}
#
# Get names and values directly
#
foreach {name value} [array get mydata] {
puts "Data on \"$name\": $value"
}
foreach name [lsort [array names mydata]] {
puts "Data on \"$name\": $mydata($name)"
}
While arrays are great as a storage facility for some purposes, they are a bit tricky when you pass them to a procedure: they are actually collections of variables. This will not work:
proc print12 {a} {
puts "$a(1), $a(2)"
}
set array(1) "A"
set array(2) "B"
print12 $array
The reason is very simple: an array does not have a value. Instead the above code should be:
proc print12 {array} {
upvar $array a
puts "$a(1), $a(2)"
}
set array(1) "A"
set array(2) "B"
print12 array
So, instead of passing a "value" for the array, you pass the name