ArrayName ( ArrayIndex ) |
set color(0) purple set color(1) red set color(2) red puts "$color(0) $color(1) $color(2)" // Prints: purple ... NOTES: puts $color(0) $color(1) $color(2) // Error: puts needs 1 arg ! puts {$color(0) $color(1) $color(2)} // Prints: $color(0)... |
array size ARRAY-NAME |
returns the number of elements in the array ARRAY-NAME
set color(0) purple set color(1) red set color(2) red |
(you can ofcourse use integers as array index if you so desire !).
Such an array is called an associative array
set color(myHouse) purple set color(myCar) red set color(myChair) red puts "$color(myHouse) $color(myCar) $color(myChair)" // Prints: purple red red |
array names ARRAY-NAME |
set color(myHouse) purple set color(myCar) red set color(myChair) red array names color Output: myCar myChair myHouse |
set myList { {item1} {item2} ... } |
A list item can be composite !
list "item1" "item2" ... |
In this case, you should save the return value of the command in a variable:
set myList [list "item1" "item2" ...] |
set list1 {abc def klm xyz} set list2 { {jan 1} {feb 2} {march 3} } |
A list in Tcl is a serie of items (very much like an array of dynamic size).
lindex LIST INDEX |
lindex { abc def klm xyz } 1 Returns: def |
We still need to know how many elements are in the list so that we can use a for-loop to iterate through all elements.
llength LIST |
llength { abc def klm xyz } Result: 4 |
foreach VARIABLE_NAME LIST BODY |
|
foreach i { abc klm xyz } { puts "Hello $i" } Output: Hello abc Hello klm Hello xyz |
Hence, the following loop construct will access all elements in the list:
set LIST { ...... } |
set list1 { abc def klm xyz } for {set i 0} {$i < [llength $list2]} {incr i} { puts [lindex $list1 $i] } Output: abc def klm xyz |
set color(myHouse) purple set color(myCar) red set color(myChair) red array names color Output (list): myCar myChair myHouse |
set LIST [array names color] |
set color(myHouse) purple set color(myCar) red set color(myChair) red set LIST [array names color] LIST = myCar myChair myHouse |
set color(myHouse) purple set color(myCar) red set color(myChair) red set LIST [array names color] llength $LIST |
set color(myHouse) purple set color(myCar) red set color(myChair) red set LIST [array names color] |