Associative Arrays

Table of Contents

Associative Arrays.
Example

Associative Arrays.

Languages like C, BASIC, FORTRAN and Java support arrays in which the index value is an integer. Tcl, like most scripting languages (Perl, Python, PHP, etc...) supports associative arrays (also known as "hash tables") in which the index value is a string.

The syntax for an associative array is to put the index within parentheses:


set name(first) "Mary"
set name(last)  "Poppins"

puts "Full name: $name(first) $name(last)"

There are several array commands aside from simply accessing and creating arrays which will be discussed in this and the next lesson.

array exists arrayName

Returns 1 if

arrayName is an array variable. Returns 0 if

arrayName is a scalar variable, proc, or does not exist.

array names arrayName ?pattern

Returns a list of the indices for the associative array

arrayName. If

pattern is supplied, only those indices that match

pattern are returned. The match is done using the globbing technique from

string match.

array size arrayName

Returns the number of elements in array

arrayName.

array get arrayName

Returns a list in which each odd member of the list (1, 3, 5, etc) is an index into the associative array. The list element following a name is the value of that array member.

array set arrayName dataList

Converts a list into an associative array.

DataList is a list in the format of that returned by

array get. Each odd member of the list (1, 3, 5, etc) is an index into the associative array, and the list element following that is the value of that array member.

array unset arrayName ?pattern?

Unsets all of the elements in the array. If

pattern exists, only the elements that match pattern are unset.

When an associative array name is given as the argument to the global command, all the elements of the associative array become available to that proc. For this reason, Brent Welch Practical Programming in Tcl and Tk

This method makes it simpler to share data between many procs that are working together, and doesn't pollute the global namespace as badly as using separate globals for all shared data items.

Another common use for arrays is to store tables of data. In the example below we use an array to store a simple database of names.