The list is the basic Tcl data structure. A list is simply an ordered collection of stuff; numbers, words, strings, or other lists. Even commands in Tcl are just lists 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
splitcommand - set lst [split "item 1.item 2.item 3" "."]
- with the
listcommand. - 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?...?argN?- makes a list of the arguments
splitstring?splitChars?- Splits the
stringinto a list of items wherever thesplitCharsoccur in the code.SplitCharsdefaults to being whitespace. Note that if there are two or moresplitCharsthen each one will be used individually to split the string. In other words:split "1234567" "36"would return the following list: {12 45 7}. lindexlistindex- Returns the
index'th item from the list. Note: lists start from 0, not 1, so the first item is at index 0, the second item is at index 1, and so on. llengthlist- Returns the number of elements in a list.
The items in list can be iterated through using the
foreach command:foreachvarnamelistbody- The
foreachcommand will execute thebodycode one time for each list item inlist. On each pass,varnamewill contain the value of the nextlistitem.
In reality, the above form of
foreach is the simple form, but the command is quite powerful. It will allow you to take more than one variable at a time from the list: foreach {a b} $listofpairs { ... }. You can even take a variable at a time from multiple lists! For example: foreach a $listOfA b $listOfB { ... }Examples
set x "a b c"
puts "Item at index 2 of the list {$x} is: [lindex $x 2]\n"
set y [split 7/4/1776 "/"]
index $y 1]'th day of the [lindex $y 0]'th month\n"
set z [list puts "arg 2 is
puts "We celebrate on the [
l $y" ]
puts "A command resembles: $z\n"
set i 0
foreach j $x {
puts "$j is item number $i in list x"
incr i
}

0 Comment:
Post a Comment