Version 5 of array startsearch

Updated 2013-04-18 02:38:25 by RLE

array startsearch arrayName

This command initializes an element-by-element search through the array given by arrayName, such that invocations of the array nextelement command will return the names of the individual elements in the array. When the search has been completed, the array donesearch command should be invoked. The return value is a search identifier that must be used in array nextelement and array donesearch commands; it allows multiple searches to be underway simultaneously for the same array.


Note that this may not work correctly with the special env array.


example of use of array startsearch, nextelement:

array set test {0 a 1 b 2 c 3 d 4 f} ;# create an array.
array get test ;# prints the array to show it is in random order

set srch [array startsearch test]
while {[array anymore test $srch]} {
   set key [array nextelement test $srch]
   puts "test($key) = $test($key)"
}
array donesearch test $srch ;# releases temporary memory associated with the search

The "array get test" returns:

4 f 0 a 1 b 2 c 3 d

The loop prints:

test(4) = f
test(0) = a
test(1) = b
test(2) = c
test(3) = d

NB using

while {[set key [array nextelement test $srch] != ""} ... is bad since IF the array contains a key "" the test will terminate early. Which it can.


See also: