Académique Documents
Professionnel Documents
Culture Documents
Program Invocation
Tcl can be invoked from a shell command prompt with the following syntax: tclsh [<filename> <arg0> <arg1> ...] Where tclsh is mandatory. Other input arguments are optional.
without input argument, the shell enters Tcl environment where it waits for
the Tcl statements line by line. If <filename> is specified, Tcl will interpret the text specified in the file
A Simple Example
# convert.tcl # Fahrenheit to Celsius Conversion 1. proc tempconv {} { 2. set lower 0 3. set upper 140 4. set step 25 5. set fahr $lower 6. while {fahr < $upper} { 7. set celsius [expr 5*($fahr - 32)/9] 8. puts "Fahrenheit / Celsius : $fahr / $celsius 9. set fahr [expr $fahr + $step] 10. } 11. }
6.
The while loop in Lines 610 controls the iteration of the procedure through the test
expression enclosed in a double quotation mark.
7.
The command puts in Line 8 prints out the string contained within the quotation mark.
If the name of the script is convert.tcl, the script can be executed by typing the following on a shell prompt: >>tclsh convert.tcl If the name of the script is convert.tcl, the script can be executed by typing the following on a shell prompt: >>tclsh convert.tcl Fahrenheit / Celsius : 0 / -17.778 Fahrenheit / Celsius : 25 / -3.889 Fahrenheit / Celsius : 50 / 10 Fahrenheit / Celsius : 75 / 23.889 Fahrenheit / Celsius : 100 / 37.778 Fahrenheit / Celsius : 125 / 51.667 Alternatively, since NS2 is written in Tcl, the following invocation would lead to the same result. >>ns convert.tcl
Data Types
As an interpreter, Tcl does not need to define data type of variables. Instead, it stores everything in string and interprets them based on the context. Example A.2. Consider the following Tcl codes: # vars.tcl 1. set a "10+1 2. set b "5 3. set c $a$b 4. set d [expr $a$b] 5. puts $c 6. puts $d 7. unset c 8. puts $c After executing the Tcl script vars.tcl, the following result should appear on the screen: >>tclsh vars.tcl 10+15 25
Bracketing
There are four type of bracketing in Tcl. These are used to group a series of strings.
Curly braces ({expr $var + 1}): Tcl interprets this statement as it is.
Ex: set var 10; set v {expr $var+1}; puts $v;
Quotation marks ("expr $var + 1"): Tcl interpolates the variable var in the string. This statement would be interpreted as expr 10 + 1.
Square brackets ([expr $var + 1]): It interprets the string in a square bracket before interpreting the entire line. This statement would be interpreted as 11.
Parentheses (( )): Tcl uses a parentheses for indexing an array and for invoking built-
in mathematical function.
Arrays
# Numeric indexing set arr(0) 1 set arr(1) 3 set arr(1) 5 # String indexing
puts $age(Smith)
set x [expr $age(Smith) + $length($s)]
array:
set a(1) 0 set a(foo) 1 set a(xy") bar puts [array names a]
Unsetting Arrays
The unset command works on both array elements and entire arrays.
Iterating Over Associative Arrays foreach i [array names a] {
Lists
A Tcl list holds a sequence of elements, each of which can be a number, a
At this point, the variable user_preferences is a three-element list. We can pull individual items out with lindex:
The command lsearch returns the index of the list element matching a query argument or -1 if unsuccessful:
Suppose that User A marries User B. You want to combine their preferences into a
. The following two statement are equivalent (i) set mylist "1 2 3" (ii) set mylist {1 2 3}
Member retrieval: The following command returns the nth (= {0, 1, }) element in a
list mylist:
lindex $mylist $n Member setting: The following command sets the value of the nth element in a list mylist to be <value>: lset $mylist $n $value Group retrieval: The following command returns a list whose members are the nth member through the mth member of a list mylist: lrange $mylist $n $m Appending the list: The following command attaches a list alist to the end of a list mylist: lappend $mylist $alist
Input/Output
Tcl employs a so-called Tcl channel to receive an input using a command
Tcl Channels
A Tcl channel refers to an interface used to interact to the outside world.
Two main types of Tcl channels include standard reading/writing channels and file channels. The standard reading/writing channels are classified into stdin for reading, stdout for writing, and stderr for error reporting. The file channels needs to be attached to a file before it is usable. The syntax for attaching a file to a Tcl file channel is shown below: open <filename> [<access>] This command returns a Tcl channel attached to a file with the name <filename>. The optional input argument <access> could be r for reading, w for writing to a new file, or a for appending an existing file. When a Tcl channel is no longer in use, it can be closed by using the command close whose syntax is as follows: close <channel> where <chanel> is the Tcl channel which need to be closed.
Here, all the characters in the current line from the channel will be stored
in the variable <var>.
Normally, the command puts does not output immediately onto a Tcl channel.
Instead, it puts the input argument (i.e., string) in its buffer, and releases the stored string either when the buffer is full or when the channel is closed. To force the
Example Tcl code: puts "Press any key to continue..." gets stdin set ch_in [open "input.txt" r] set ch_out [open "output.txt" "a"] set line_no 0 while {[gets $ch_in line] >= 0} { puts $ch_out "[incr line_no] $line" }
Reads line from channel and verifies , is it end of file Writes line read from input.txt along with line number Opne output.txt in append mode Open input .txt in read mode
close $ch_in
close $ch_out
Control Structure
if/else/elseif An if/else/elseif command provides a program with a selective choice. A general form of this command is shown below: if {<condition1>} { <actions_1>
} elseif {<condition2>} {
<actions_2> }else {
<actions_n>
}
Procedures
A procedure is usually used in place of a series of Tcl statements to tidy up the program. The syntax of a procedure is shown below: proc <name> {<arg_1> <arg_2> ... <arg_n>} { <actions> [return <returned_value>] }
After defining a procedure, one may invoke the procedure by executing the following statement: set var [<name> <value_1> <value_2> <value_n>] where var is set to the value returned from the procedure <name>, and the values <value_1> <value_2> <value_n> are fed as input arguments of the procedure.
while/for/foreach
The commands while, for, and foreach are used when actions need to be repeated for
several times. while {<condition>} {
<actions>
} for {<init>} {<condition>} {<mod>} {
<actions>
} foreach {<var>} {<list>} { <actions> }
Global Variables
Global variables are common and used extensively throughout a program.
OTCL
Objects
Tcl itself does not support objects, but the OTcl extension, used by ns2, does.
Example is a counter class with a constructor and three methods. The constructor will initialize an instance variable to zero. There will be two methods to increment
and decrement this variable. There will be one more function to get the value of the
variable. The code is show in the listing below.
We define the constructor on line 3. The constructor is just a regular function with a
special name: init. To add functions to the class, we use instproc. On line 3 we define a new function
called init that takes no arguments. Defining functions of the class is just like
defining commands, except instead of proc you use <ClassName> instproc. Classes can have instance variables that are accessed through the self variable as
shown in line 4. All functions of the class have access to any instance variables. Line
4 says that we want to access an instance variable called value. In the rest of the function, we can use value as a regular variable and anything we
do to it here will be seen by all other functions of the class. In this case, on line 5 we
initialize it to zero. After init is called, any other function accessing the value variable will see its value as zero.
On line 20, we create an instance of the Counter class and store it in the count
variable. Using new will call the constructor (the init method). The remaining three
lines show how we can call functions on the object. The square brackets are again used to get the return value.
Example
Consider a general network node. When equipped with mobility, this node
becomes a mobile node. Declaration of a class Node and its child class
Mobile is shown below. This declaration allows class Mobile to inherit capabilities of class Node (e.g., receiving packets) and to include more