Lists and arrays

A list is a way to group data and handle the group as a single entity. To define a list, use curly braces { } and double quotes “ “. For example, the following set command {1 2 3 }, when followed by the list command, creates a list stored in the variable "a." This list will contain the items "1," "2," and "3."

set a { 1 2 3 }

Here's another example:

set e 2

set f 3

set a [ list b c d [ expr $e + $f ] ]

puts $a

displays (or outputs):

b c d 5

Tcl supports many other list-related commands such as lindex, linsert, llength, lrange, and lappend. For more information, refer to one of the books or web sites available on this subject.

Arrays

An array is another way to group data. Arrays are collections of items stored in variables. Each item has a unique address that you use to access it. You do not need to declare them nor specify their size.

Array elements are handled in the same way as other Tcl variables. You create them with the set command, and you can use the dollar sign ($) for their values.

set myarray(0) "Zero"

set myarray(1) "One"

set myarray(2) "Two"

for {set i 0} {$i < 3} {incr i 1} {

    puts $myarray($i)

}

      

Output:

Zero

One

Two

 

In the example above, an array called "myarray" is created by the set statement that assigns a value to its first element. The for-loop statement prints out the value stored in each element of the array.

Special arguments (command-line parameters)

You can determine the name of the Tcl script file while executing the Tcl script by referring to the $argv0 variable.

puts “Executing file $argv0”

 

To access other arguments from the command line, you can use the lindex command and the argv variable:

To read the the Tcl file name:

lindex $argv 0

 

To read the first passed argument:

lindex $argv 1

 

Example

puts "Script name is $argv0" ; # accessing the scriptname

puts "first argument is [lindex $argv 0]"

puts "second argument is [lindex $argv 1]"

puts "third argument is [lindex $argv 2]"

puts "number of argument is [llength $argv]"

set des_name [lindex $argv 0]

puts "Design name is $des_name"