Version 18 of array get

Updated 2018-08-12 05:12:07 by pooryorick

array get retrieves values in an array.

Synopsis

array get arrayName ?pattern?

Description

Returns a list containing pairs of elements. The first element in each pair is the name of an element in arrayName and the second element of each pair is the value of the array element. The order of the pairs is undefined. If pattern is not specified, then all of the elements of the array are included in the result. If pattern is specified, then only those elements whose names match pattern (using the matching rules of string match) are included. If arrayName isn't the name of an array variable, or if the array contains no elements, then an empty list is returned.

A common use for array get is to wrap an array up and store it as a value (pass it to a command, stick it into another array, or whatever). array set will conversely expand the value out into an array again, so that the elements are easily accessable.

 array set targetArray [array get sourceArray]

Of course, as of Tcl 8.5 there is the dict command which operates directly on the "wrapped form" of an array.


RR 2003-12-29: It is very likely obvious to even moderately experienced Tcl'rs how to sort the return from "array get" in indexed order but the following might be useful to novices:

proc iSort {listin} {
    foreach {a b} $listin {lappend lout [list $a $b]}
    return [lsort -index 0 $lout]
}

The elements of the list returned by "array get", as stated above, alternate between element name and element value in the array. Regardless of the dimension of the array, the element name is a single list element containing the index (like: "0", or "a,b,c", or "month,day"). They come out of "array get" in any and every order imaginable, but always as {elementName elementValue} pairs. To make them more readable, sublist them into those pairs and sort the "super-list"

Lars H 2003-12-30: Modified the code to prevent shimmering (and to some extent garbling) of the data. If the sort key is only part of a list element, then it is usually better to use the -index option than to sort on the whole elements, since the latter forces conversions to string representation.

dougcosine 2014-04-23: iSort above returns a different sort of list than what is passed as listin. For instance:

> iSort {1 b 0 a}
{0 a} {1 b}

rather than:

> iSort {1 b 0 a}
0 a 1 b

Adding a join to the return statement fixes this:

proc iSort {listin} {
    foreach {a b} $listin {lappend lout [list $a $b]}
    return [join [lsort -index 0 $lout]]
}

Martyn Smith If you are using Tcl 8.6 you can use the -stride option:

lsort -stride 2 [array get Array]