You are here:Home » Tcl » Arrays in Tcl programming

Arrays in Tcl programming

Arrays in Tcl

In this part of the Tcl programming tutorial, we will cover arrays. We will initiate arrays and read data from them.
An array in Tcl is a data structure, which binds a key with a value. A key and a value can be any Tcl string.
#!/usr/bin/tclsh

set names(1) Jane
set names(2) Tom
set names(3) Elisabeth
set names(4) Robert
set names(5) Julia
set names(6) Victoria

puts [array exists names]
puts [array size names]

puts $names(1)
puts $names(2)
puts $names(6)
We create a names array. The numbers are keys and the names are values of the array.
set names(1) Jane
In this line we set a value Jane to the array key 1. We can later refer to the value by the key.
puts [array exists names]
The array exists command determines, whether the array is created. Returns 1 if true, 0 otherwise.
puts [array size names]
We get the size of the array with the array size command.
puts $names(1)
We access a value from the array by its key.
$ ./names.tcl
1
6
Jane
Tom
Victoria
Output.

Arrays can be initiated with the array setcommand.
#!/usr/bin/tclsh

array set days {
1 Monday
2 Tuesday
3 Wednesday
4 Thursday
5 Friday
6 Saturday
7 Sunday
}

foreach {n day} [array get days] {

puts "$n -> $day"
}
We create a day array. It has 7 keys and values.
foreach {n day} [array get days] {
The array get command returns a list of key, value elements, which can be iterated with the foreach command.
$ ./days.tcl
4 -> Thursday
5 -> Friday
1 -> Monday
6 -> Saturday
2 -> Tuesday
7 -> Sunday
3 -> Wednesday
Output.

We show another way to traverse an array in Tcl.
#!/usr/bin/tclsh

array set nums { a 1 b 2 c 3 d 4 e 5 }

puts [array names nums]

foreach n [array names nums] {

puts $nums($n)
}
The script uses the array names command to traverse the array.
array set nums { a 1 b 2 c 3 d 4 e 5 }
We define a simple array.
puts [array names nums]
The array names returns a list containing the names of all of the elements in the array.
foreach n [array names nums] {

puts $nums($n)
}
We use the keys to get the values.
$ ./getnames.tcl 
d e a b c
4
5
1
2
3
Output.

In the last example of this chapter, we will show how to remove elements from the array.
#!/usr/bin/tclsh

set names(1) Jane
set names(2) Tom
set names(3) Elisabeth
set names(4) Robert
set names(5) Julia
set names(6) Victoria

puts [array size names]
unset names(1)
unset names(2)

puts [array size names]
We create a names array. We use the unset command to remove items from the array. We check the size of the array before and after we remove the two items.
set names(1) Jane
The set command is used to create an item in the array.
unset names(1)
We use the unset command to remove an element with key 1 from the array.
In this part of the Tcl tutorial, we worked with arrays.

0 comments:

Post a Comment