A Programming Essentials
Total Page:16
File Type:pdf, Size:1020Kb
A Programming Essentials This appendix covers the basic elements of the programming languages, which are essential for developing NS2 simulation programs. These include Tcl/OTcl which is the basic building block of NS2 and AWK which can be used for post simulation analysis. A.1 Tcl Programming Tcl is a general purpose scripting language. While it can do anything other languages could possibly do, its integration with other languages has proven even more powerful. Tcl runs on most of the platforms such as Unix, Windows, and Mac. The strength of Tcl is its simplicity. It is not necessary to declare a data type for variable prior to the usage. At runtime, Tcl interprets the codes line by line and converts the string into appropriate data type (e.g., integer) on the fly. A.1.1 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. When the above command is invoked without input argument, the shell enters Tcl en- vironment 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 (see Section A.1.3) argv.Inthemain program, <argi> can be retrieved by executing “lindex $argv $i”. 390 A Programming Essentials A.1.2 A Simple Example To get a feeling about the language, we look at Example A.1 below: Example A.1. The following Tcl script, “convert.tcl”, converts tempera- tures from Fahrenheit to Celsius. The conversion starts at 0 degree (Fahren- heit), proceeds with a step of 25 degrees (Fahrenheit), and stops when the temperature exceeds 140 degrees (Fahrenheit). The program prints out the converted temperature in Celsius as long as the temperature in Fahrenheit does not exceed 140 degrees. # 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 } The details of the above example are as follows. The symbol # here denotes the beginning of a line comment. The reserved word proc in Line 1 declares a procedure tempconv{} which takes no input argument. The procedure also defines four local variables (i.e., lower, upper, step,andfahr) and assigns values to them using the reserved word set followed by the name and its as- signed value (Lines 2–5). Note here that, to refer to the value of a variable, the reserved character $ is used in front of the variable (e.g., set fahr $lower). The keyword expr in Line 9 informs the Tcl interpreter to interpret the fol- lowing string as a mathematical expression. The while loop in Lines 6–10 controls the iteration of the procedure through the test expression enclosed in a double quotation mark. 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 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 A.1 Tcl Programming 391 Alternatively, since NS2 is written in Tcl, the following invocation would lead to the same result. >>ns convert.tcl A.1.3 Variables and Data Types 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 Here, variable c is simply a string “10+15”, whereas variable d is 25 ob- tained by numerically evaluating the string “10+15”storedinvariablec. Therefore, we may conclude that everything is treated as a string unless spec- ified otherwise [26]. 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 “$”infrontofa variable name. In addition, a reserved word “unset” is used to clear the value stored in a variable. Example A.3. Insert the following two lines into the end of the codes in Example A.2. 7 unset c 8 puts $c 392 A Programming Essentials After executing the Tcl script “vars.tcl”, the following result should appear on the screen: >>tclsh vars.tcl 10+15 25 can’t read "c": no such variable while executing "puts c" (file "var.tcl" line 8) Clearly after being unset,variablec stores nothing. Printing the variable would result in a runtime error. 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. • 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]): Tcl regards a square bracket in the same way that C++ regards a parenthesis. It interprets the string in a square bracket before interpreting the entire line. This statement would be interpreted as “11”. • Parentheses ((expr $var + 1)): Tcl uses a parentheses for indexing an array and for invoking built-in mathematical function. Example A.4. Insert the following two lines into the end of the codes in Example A.2. 7 puts -nonewline {{}: } 8 puts {expr $c} 9 puts -nonewline {"": } 10 puts "expr $c" 11 puts -nonewline {[]: } 12 puts [expr $c] After executing the Tcl script “vars.tcl”, the following result should appear on the screen: >>tclsh vars.tcl 10+15 25 A.1 Tcl Programming 393 {}: expr $c "": expr 10+15 []: 25 When bracketing with “{}”, Tcl interprets the string as it is; The result in this case is “expr $c”. The string $c is replaced with its value when bracketing with “""”. The result in this case is “expr 10+15”. Finally, “[]”identifies the sequence of execution. The string “expr $c” is executed first. The result in this case is “25”. Global Variables In Example A.1, we briefly mentioned about local variables. But what was missing there is the notion of global variables. Global variables are common and used extensively throughout a program. These variables can be called upon by any procedure in the program. Example A.5 shows an example use of global variables. Example A.5 (Global variables). set PI 3.1415926536 proc perimeter {radius} { global PI expr 2*$PI*$radius } Since “PI” is defined outside of the procedure perimeter,thekeyword global is used here to make “PI” global and available within the procedure. When called upon, this procedure simply calculates the perimeter of a circle based on the supplied input radius. Finally, we note here that no default values are automatically assigned to variables. Any attempt to call an unini- tialized variable would lead to a runtime error. Array An array is a special variable which can be used to store a collection of items. An array stores both the indexes and the values as strings. For example, index “0” is not a number, but a numeric string. By default, an array in Tcl is an associative array. Example A.6 below shows various ways of string manipulation. Example A.6 (Array assignment). # Numeric indexing set arr(0) 1 set arr(1) 3 set arr(1) 5 394 A Programming Essentials # String indexing set wlan(datarate) 54000000 set wlan(protocol) "tcp" Lists A list is an ordered collection of elements such as numbers, strings or even lists themselves. The key list manipulations are shown below: • List creation: A list can be created in various ways as shown in Exam- ple A.7 below. Example A.7. The following two statement are equivalent (i) set mylist "1 2 3" (ii) set mylist {123} From the above, a list can be created in three ways. First, it can be created by the reserved word list which takes list members as input arguments. Alternatively, it can be created by embracing the members within a pair of curly braces or a pair of quotation marks. • 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 ele- ment 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 A.1.4 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.