| [ Team LiB ] |
|
The array CommandThe array command returns information about array variables. The array names command returns the index names that are defined in the array. If the array variable is not defined, then array names just returns an empty list. It allows easy iteration through an array with a foreach loop: foreach index [array names arr pattern] { # use arr($index) } The order of the names returned by array names is arbitrary. It is essentially determined by the hash table implementation of the array. You can limit what names are returned by specifying a pattern that matches indices. The pattern is the kind supported by the string match command, which is described on page 53. It is also possible to iterate through the elements of an array one at a time using the search-related commands listed in Table 8-1. The ordering is also random, and I find the foreach over the results of array names much more convenient. If your array has an extremely large number of elements, or if you need to manage an iteration over a long period of time, then the array search operations might be more appropriate. Frankly, I never use them. Table 8-1 summarizes the array command:
Converting Between Arrays and ListsThe array get and array set operations are used to convert between an array and a list. The list returned by array get has an even number of elements. The first element is an index, and the next is the corresponding array value. The list elements continue to alternate between index and value. The list argument to array set must have the same structure.
array set fruit {
best kiwi
worst peach
ok banana
}
array get fruit
=> ok banana best kiwi worst peach
Another way to loop through the contents of an array is to use array get and the two-variable form of the foreach command.
foreach {key value} [array get fruit] {
# key is ok, best, or worst
# value is some fruit
}
Passing Arrays by NameThe upvar command works on arrays. You can pass an array name to a procedure and use the upvar command to get an indirect reference to the array variable in the caller's scope. This is illustrated in Example 8-4, which inverts an array. As with array names, you can specify a pattern to array get to limit what part of the array is returned. This example uses upvar because the array names are passed into the ArrayInvert procedure. The inverse array does not need to exist before you call ArrayInvert. Example 8-4 ArrayInvert inverts an array
proc ArrayInvert {arrName inverseName {pattern *}} {
upvar $arrName array $inverseName inverse
foreach {index value} [array get array $pattern] {
set inverse($value) $index
}
}
|
| [ Team LiB ] |
|