Vous êtes sur la page 1sur 35

TCL

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

whose name is <filename> line by line.


In addition, if <arg0> <arg1> ... are specified, they will be placed in a list variable argv

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. }

Details of the example


1. 2. 3. The symbol # here denotes the beginning of a line comment. The reserved word proc in Line 1 declares a procedure tempconv{} defines four local variables (i.e., lower, upper, step, and fahr) and assigns values to them using the reserved word set followed by the name and its assigned value (Lines 2 5). 4. To refer to the value of a variable, the reserved character $ is used in front of the variable. 5. The keyword expr in Line 9 informs the Tcl interpreter to interpret the following string as a mathematical expression.

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

Variable Assignment and Retrieval


Tcl stores a value in a variable using the reserved word set. The value stored in a variable can be retrieved by placing a character $ in front of a variable name. In addition, a reserved word unset is used to clear the value stored in a variable.

Bracketing
There are four type of bracketing in Tcl. These are used to group a series of strings.

Tcl interprets strings inside different types of bracket differently.


Suppose a variable $var stores a value 10. Tcl interprets a statement expr $var + 1 with four different bracketing differently.

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

set wlan(datarate) 54000000


set wlan(protocol) "tcp" Variable substitution with$ works with arrays:

puts $age(Smith)
set x [expr $age(Smith) + $length($s)]

The array names Command


The array names command returns a list of all the indices (names) of an

array:
set a(1) 0 set a(foo) 1 set a(xy") bar puts [array names a]

The array size Command


set a(1) 0 set a(foo) 1 set a("xy") bar puts [array size a] 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] {

puts "a($i): $a($i)"


} Multidimensional Arrays Tcl doesn't have multidimensional arrays, but associative arrays can simulate them easily: set a(1,1) 0 set a(1,2) 0

Lists
A Tcl list holds a sequence of elements, each of which can be a number, a

string, or another list.

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

household_preferences variable using the concat command:

. 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

gets or to send an output using a command puts.

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.

The Commands gets and puts


The command puts and gets reads and writes, respectively, a message to a specified Tcl channel. In particular, the command gets reads a line from a Tcl channel, and passes every character in the line except the end-of-line character to the Tcl running environment. If <channel> is not specified, the stdin will be used as a default channel. The Tcl channel could be a standard channel or a file channel. The syntax of the command gets is as follows: gets <channel> <var>

Here, all the characters in the current line from the channel will be stored
in the variable <var>.

The command puts writes a string <string> followed by an end-of-line character

to a Tcl channel <channel>.


If <channel> is not specified, the stdout will be used as a default channel. The syntax of the command puts is as follows:

puts [-nonewline] ]<channel>[ <string>


where the nonewline option above specifies not to write an end-of-line character to the end of the string.

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

immediate outputting, flush is used.


A file channel needs to be closed explicitly using the command close.

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.

These variables can be called upon by any procedure in the 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.

To define the class, we first give it a name, as shown on line 1.

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.

Class and Inheritance


In OTcl, a class can be declared using the following syntax: class <classname> [-superclass <superclassname>] If the optional argument in the square bracket is present, OTcl will recognize class <classname> as a child class of class <superclassname>. Alternatively, if the option is absent, class <classname> can be also declared as a

child class of class <superclassname> by executing


<classname> superclass <superclassname> Note that, class <classname> inherits the functionalities (including procedures and

variables) of class <superclassname>.


In OTcl, the top-level class is class Object, which provides basic procedures and variables, from which every user-defined class inherits.

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

capabilities (e.g., moving) to itself.


class Node class Mobile -superclass Node

Object class methods


Instproc next Invoked from within an instproc, next searches up the hierarchy (in parent classes) for an instproc with the same name, and invokes the instproc belonging to the closest parent class. Instproc info This instproc returns related information based on the input argument. It can be invoked using one of the two following ways: <object> info <arg>

<classname> info <arg>


The upper and lower invocations return the information about the object and the class, respectively.

Options of the info instproc for objects

Options of the info instproc for classes

Vous aimerez peut-être aussi