array get

array get retrieves values in an array.

Synopsis

array get arrayName ?pattern?

Description

Returns a dictionary of names and values of variables in the array, in no particular order. If pattern is not specified, then all of the variables in the array are included in the result. If pattern is specified, then only those variables 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 is empty, 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.

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]
}

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]