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/tclshWe create a names array. The numbers are keys and the names are values of the array.
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)
set names(1) JaneIn 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.tclOutput.
1
6
Jane
Tom
Victoria
Arrays can be initiated with the
array set
command. #!/usr/bin/tclshWe create a day array. It has 7 keys and values.
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"
}
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.tclOutput.
4 -> Thursday
5 -> Friday
1 -> Monday
6 -> Saturday
2 -> Tuesday
7 -> Sunday
3 -> Wednesday
We show another way to traverse an array in Tcl.
#!/usr/bin/tclshThe script uses the
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)
}
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] {We use the keys to get the values.
puts $nums($n)
}
$ ./getnames.tclOutput.
d e a b c
4
5
1
2
3
In the last example of this chapter, we will show how to remove elements from the array.
#!/usr/bin/tclshWe create a names array. We use the
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]
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) JaneThe
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