Tcl - Arrays



An array is a systematic arrangement of a group of elements using indices. The syntax for the conventional array is shown below.

set ArrayName(Index) value

An example for creating simple array is shown below.

#!/usr/bin/tclsh

set languages(0) Tcl
set languages(1) "C Language"
puts $languages(0)
puts $languages(1)

When the above code is executed, it produces the following result −

Tcl
C Language

Size of Array

The syntax for calculating size array is shown below.

[array size variablename]

An example for printing the size is shown below.

#!/usr/bin/tclsh

set languages(0) Tcl
set languages(1) "C Language"
puts  [array size languages]

When the above code is executed, it produces the following result −

2

Array Iteration

Though, array indices can be non-continuous like values specified for index 1 then index 10 and so on. But, in case they are continuous, we can use array iteration to access elements of the array. A simple array iteration for printing elements of the array is shown below.

#!/usr/bin/tclsh

set languages(0) Tcl
set languages(1) "C Language"
for { set index 0 }  { $index < [array size languages] }  { incr index } {
   puts "languages($index) : $languages($index)"
}

When the above code is executed, it produces the following result −

languages(0) : Tcl
languages(1) : C Language

Associative Arrays

In Tcl, all arrays by nature are associative. Arrays are stored and retrieved without any specific order. Associative arrays have an index that is not necessarily a number, and can be sparsely populated. A simple example for associative array with non-number indices is shown below.

#!/usr/bin/tclsh

set personA(Name) "Dave"
set personA(Age) 14
puts  $personA(Name)
puts  $personA(Age)

When the above code is executed, it produces the following result −

Dave
14

Indices of Array

The syntax for retrieving indices of array is shown below.

[array names variablename]

An example for printing the size is shown below.

#!/usr/bin/tclsh

set personA(Name) "Dave"
set personA(Age) 14
puts [array names personA]

When the above code is executed, it produces the following result −

Age Name

Iteration of Associative Array

You can use the indices of array to iterate through the associative array. An example is shown below.

#!/usr/bin/tclsh

set personA(Name) "Dave"
set personA(Age) 14
foreach index [array names personA] {
   puts "personA($index): $personA($index)"
}

When the above code is executed, it produces the following result −

personA(Age): 14
personA(Name): Dave
Advertisements