Tcl/Tk Tutorial on 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