. Tcl Data Structures 101 - The list .
[ Previous | Index | Next ]
The list is the basic data structure to Tcl. A list is simply an ordered collection of stuff; numbers, words, strings, etc. For instance, a command in Tcl is just a list in which the first list entry is the name of a proc, and subsequent members of the list are the arguments to the proc.
Lists can be created in several ways:
- by setting a variable to be a list of values
- set lst {{item 1} {item 2} {item 3}}
- with the split command
- set lst [split "item 1.item 2.item 3" "."]
- with the list command.
- set lst [list "item 1" "item 2" "item 3"]
An individual list member can be accessed with the lindex command.
The brief description of these commands is:
- list
?arg1 arg2 ...?
- makes a list of the arguments
- split string ?splitChars?
- Splits the string into a list of items at splitChars. SplitChars defaults to being whitespace. Note that if there are two splitChars in a row in the string being split, then each be parsed as marking a list entry, and will create an empty entry in the list. If splitChars is a string, then each member of the string will be used to split string into list members. Ie: split "1234567" "36"] would split into a list composed of {12 45 7}.
- lindex list index
- returns the index'th item from the list. The first item is 0.
- llength list
- Returns the number of elements in a list.
The items in list can be iterated through using the foreach command.
foreach varname list body
Foreach will execute the body code one time for each list item in list. On each pass, varname will contain the value of the next list item.
--
. Example .
set x "a b c"
puts "Item 2 of the list {$x} is: [lindex $x 2]\n"
set y [split 7/4/1776 "/"]
puts "We celebrate on the [lindex $y 1]'th day of the [lindex $y 0]'th month\n"
set z [list puts "arg 2 is $y" ]
puts "A command resembles: $z\n"
set i 0;
foreach j $x {
puts "$j is item number $i in list x"
incr i;
}
|