Associative or multi dimenstional arrays in TCL

Associative Arrays

Associative arrays are an important generalization of common arrays.

  • Arrays in most languages can only be indexed by integers (sometimes only by non-negative integers).
  • Arrays in Tcl are indexed by arbitrary strings.
  • Associative arrays can be used like common arrays simply by only using numbers to index them.

Tcl’s associative arrays are implemented as hash tables for efficiency.

History of Associative Arrays

Associative arrays were first used in the programming language Snobol4 in the mid-1960s. They are a very common data structure in the Unix environment, being provided as the major data structure by languages like Awk, Perl, etc.

Uses of Associative Arrays

Associative arrays can be used to represent 1- and N-dimensional arrays, sequential structures like lists and queues (though Tcl provides these natively), symbol tables, Cartesian products (i.e., the structs of C, the records of Pascal), graphs, sets, and more.

Accessing Associative Array Elements

There is a special notation for array names which is used to access array elements:


    set a(1) 0
    set salary(Smith) 30000
    set age(Smith) 45
    set "x(white space)" foo
    set s "This is a kind of long string"
    set length($s) [string length $s]

Variable substitution with$ works with arrays:


    puts $age(Smith)
    expr $age(Smith) + $length($s)

Note the difference between these forms:


    set {white space(Smith)} foo
    puts ${white space}(Smith)
    puts ${white space(Smith)}
    puts [set {white space(Smith)}]

The array names Command

The array names command returns a list of all the indices (names) of an array:


    set a(1) 0
    set a(foo) 1
    set a("x y") bar
    array names a
    => foo {x y} 1

The indices are returned in random order, because the array elements are stored in random order.

The array size Command

The array size command returns the number of elements in an array:


    array size a
    => 3

expr [array size a] == [llength [array names a]] will always be 1 (true) for any array a

Unsetting Arrays

The unset command works on both array elements and entire arrays.

Iterating Over Associative Arrays

    foreach i [array names a] {
	puts "a($i): $a($i)"

Multidimensional Arrays

Tcl doesn’t have multidimensional arrays, but associative arrays can simulate them easily:


    set a(1,1) 0
    set a(1,2) 0
    set a(1,3) 0
    set a(2,1) 0
    set a(2,2) 0
    set a(2,3) 0

This works because the array indices are, as always, strings.













Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s