21.1.9 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 is 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.

21.1.9.1 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} {

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.

21.1.9.2 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 Tcl file name:

lindex $argv 0

To read the first passed argument:

lindex $argv 1

For 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"