You are on page 1of 73

Programming Essentials

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

Outline
Tcl/Otcl
Tcl Regular Expression OTcl

Unix Essentials

Summary y

Redirection Command AWK Grep

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

Overview, Syntax, and Example Data type: String, List, Associative array, y Handle Input/Output, Mathematical functions Control Structures Procedure

T l: Outline Tcl: O tlin

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

An Interpreter:

T l: Overview Tcl: O i

Interpret instructions lines by lines No need for compilation

Core language for NS2 Strength: Simplicity


Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

N t ti n Notation
>> : Command C d prompt t foo : A string foo <foo> : The Th value l stored t d in i variable i bl foo [foo] : Optional placement of foo

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

Program invocation

T l Program Tcl: P Invocation I ti

>> tclsh [<filename> [<args>] g ] >> ns [<filename> [<args>] ] N No input i arg = Enter E Tcl T l environment; i Take command line by line <filename> = an input Tcl file name <args> = input arguments separated by white spaces
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

T l Program Tcl: P Invocation I ti


<filename> = Tcl script p or Simualtion

script

From F within ithi th the simulation i l ti script i t

The input argument <args> is stored in an array $argv The number of input arguments is stored in a variable $argc To T retrieve i nth (={0,1,}) ( {0 1 }) i input argument, execute
lindex $ $argv g $ $n

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

Position based ( (not keyword-based) y )


First word = Tcl command

T l: Syntax Tcl: S nt x

Each word separated by a white space Termination = EOL or Semicolon ; $ = Interpretation p of variable

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

Grouping p g

T l: Syntax Tcl: S nt x

<str>: evaluation of <str> {<str>}: <str> with value substitution [<str>]: <str> without value substitution (<str>): the index <str>

\ = disable the special character # = comment t

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

T l Simple Tcl: Si l Example E l


Convert temperature from Fahrenheit (Tf) to Celsius (Tc):
Tc = f(Tf) = [ (Tf -32) 32) *5/9 5/9 ]

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

10

T l Data Tcl: D Type--String T S i


Main Data Type = string, string list, list associative array String: Example
# var var.tcl tcl

>> tclsh t l h var.tcl t l ( 10 + 15 ) ( 25 )

Quiz: $c stores ( 10 + 15 )
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

11

T l String Tcl: S i
Default type set: Value assignment / Retrieval set <name> <expr> set the value of $<name> to <expr> $<name> set return the value stored in $<name> unset <name> Remove the value stored in <name>

append <varname> <val1> <val2> Append <val1> val1 <val2> val2 to the variable <name> name

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

12

T l String Tcl: S i
From the previous example, example insert
unset c puts $c

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

13

T l String Tcl: S i
Command: string, g, format, , scan Command string:

string match <pattern> <string>:


Return 1 if matched; 0 otherwise <pattern> Use Regular Expression

string tolower: change to lower case string toupper: change h to upper case string length: return no. of characters
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

14

T l String Tcl: S i
Command string g( (cont.): ) string first <str>: return the first occurrence of <str> string last <str>: return the last occurrence of <str> string range <str> <f> <l>: return the characters in <str> between <f> position and <l> position

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

15

Command format <fmt> <f t> < <v1> 1> < <v2> 2> similar to p printf in C++ Return the formated string
Format %s %c Meaning g String Ascii Equivalent (of input integer) Format Meaning g %x or %X Hexadecimal %f Floating point %e or %E Scientific Representation %g or %G Either Ei h %f or %e
16

T l String Tcl: S i

%d or %i Integer %u %o d value l Unsigned Octal

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

Command

T l String Tcl: S i

scan <str> <fmt> <v1> <v2>

Reverse of format Parse <str> Look for format <fmt> Place relevant values in <v1> <v2> Regular Expression can be used in
<str>

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

17

Similar to arrays Use {} to


Create a list Create a sublist {} = empty list

T l List Tcl: Li

Commands: C d set, list, lappend,


split, join, llength, lindex, linsert, , lreplace p
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

18

T l List Tcl: Li
List Creation: Use either
set mylist [list 1 2 3] set mylist 1 2 3 set mylist {1 2 3}

M Member b retrieval t i l: R Retrieve t i th the nth (={0,1,}) member of the list lindex $mylist <n> Quiz: lindex $mylist 1 returns ( 2 )
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

19

T l List Tcl: Li
Member setting:
lset mylist <n> <value>

G Group retrieval/replace i l/ l setting: i Return a list containing the nth to mth member b of f the h list li
lrange $mylist <n> <m> lreplace $mylist <n> <m> <e1> <e2>

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

20

T l List Tcl: Li
List Appending: String Length
l lappend d $mylist $ li t $ $anotherlist th li t llength $mylist

Convert List to String: Convert String to List:

join <list1> <list2>

spit <str> <separator>


Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

21

T l Associative Tcl: A i i A Array


An array y with string g indices Creation:
set price(apple) 10 set price(orange) 20 array <name> <arr> [<pattern>]:

Return u a list containing g all index values u of f <arr>. Return only indices which match the <pattern>. Return indices and values of <arr>

array get <arr>:

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

22

T l Handle Tcl: H dl
An object j return by y Tcl Channel: a file, a serial port, or a TCP socket Graphic: a graphic object http: h a ref. f to a URL We shall focus on channel channel Discuss later in file access

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

23

T l Input/Output Tcl: I /O
Tcl Channel: Channel Interface to the outside world (4 types) ?? 1. Standard input: stdin ?? 2. Standard output: stdout 3. Standard error: stderr {r,w,a,r+,w+,a+} 4. File channel
To obtain the channel To close the file
close <channel> open <filename> [<acc [<acc_type>] type>]

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

24

T l Input/Output Tcl: I /O
gets: Read from the channel gets <channel> <var> puts: Write to the channel puts [-nonewline] [<channel>] <string>

Example: Copy input input.txt txt to output.txt output txt


Wait for end of line

Write to the output file (output.txt)


Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

25

T l Mathematics Tcl: M h i
incr: expr:

Increment Tell Tcl that the following is a mathematical expression.

expr <operand1> <operator> <operand2> expr <function>(<arg>) f ti ( )

Example:
Operator: Function:
expr $a + 3 expr log10(10)
26

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

T l Mathematics Tcl: M h i
Lists of operators:

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

27

T l Mathematics Tcl: M h i
Lists of functions:

returns a floating point rand returns a random number in [0,1] srand returns a random integer g wide returns an integer part hypot returns
double
[1] http://www.tcl.tk/man/tcl8.5/TclCmd/mathfunc.htm [2] C. Flynt, Tcl/Tk: A developer guide, Morgan Kaufmann, 2003.
28

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

T l Control Tcl: C l Structure S


if/else/elseif

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

29

T l Control Tcl: C l Structure S


switch

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

30

T l Control Tcl: C l Structure S


while/for/foreach

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

31

T l Procedures Tcl: P d
Definition:
proc <proc_name> { <arg1> <argn> } { <actions> return <returned_value> }

Invocation:
<proc_name> <val1> <valn>

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

32

T l Procedures Tcl: P d
Global scope: use
global <varname1> <varname2>

Global Information Variable: Variable Meaning $argv A list of input argument $ $argc Th number The b of f elements l ts i in $argv $ $env An associative array of environment variables
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

33

Outline
Tcl/Otcl
Tcl Regular Expression OTcl

Unix Essentials

Summary y

Redirection Command AWK Grep

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

34

R Regular l E Expression i
Syntax for String Matching Tcl, Perl, AWK, etc. gy Terminology

Example:

Rules = Piece: Matching rule Target String: A string to be search Atom: A character in a target string Count Modifier: Modify the number of matching

Is there h any n [or more] in the h string This h is the h beginning b


Matched!!
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

35

Atom
Atom
X [ [a-x] ] . ^ $ \

Meaning A character X A character Any h t within ithi a to t x Any character (e.g., a.c match abc) Beginning of the target string only (e.g., (e g ^a ^ ) ) End of the target string only (e.g., z$) Inhibit special character

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

36

Count Modifier
Syntax y
Modifier
x? x+ x*

Meaning Zero or One occurrence of fx One or More occurrence of x Zero or More occurrence of x 0 Color N/A Color 1 Colour Colour Colour 2 or more N/A Colouur Colouur
37

Example
Regex g Colou?r Colou+r Colou*r

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

Range
Range
[abc] [a-z] [^a] [^a-z]

Meaning a, b, or c Any character from a to z Any y character except p a Any character except a to z

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

38

T l Invocation Tcl I i
Find a match
regexp [<opt>] <pattern> <str> <varF> <varS1> <varS2>

<opt>:

option <pattern>: pattern to be matched <str>: given string <varF>: put the result of the entire match here
<var1>, < 1> < <var2>, 2> <pattern> may contain several parts, each enclosed by (). Put 1st, 2nd , part in <var1>, <var2>,

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

39

T l Invocation Tcl I i
Substitution
regsub [<opt>] <pattern> <str> <substr> <var>

<substr>:

string to substitute the matched string <var>: put the modified string here

Example
regexp ABcdEF{([A-Z]*)((a-z)*[A-Z]*)} a b c d e
regsub wrung This is wrong!! result

What Wh t are stored t d in i $a, $b,$c, $d, $e, and d $result?


Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

40

Outline
Tcl/Otcl
Tcl Regular Expression OTcl

Unix Essentials

Summary y

Redirection Command AWK Grep

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

41

OT l Outline OTcl: O li
Overview Example Syntax Useful methods

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

42

OT l Overview OTcl: O i
Object oriented Tcl (OTcl) Class:
A collection ll ti of f common thi things Attributes State or Memory Methods What to do Instvar Instproc

Objects and Instances Inheritance

Base class = Mother class = Parent class Derived class = child class
43

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

OT l Example OTcl: E l
Base Class = Class Node
Instvar = state Instproc = recv() ( )

Derived Class = Class Mobile


Derive all ll instvars and instprocs from class Node Instvar I t = location Instproc = move()
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

44

BASE CLASS
Class Node

OTcl: Example
recv(pkt)

state

Derive

Class Mobile

location

move(x,y) recv_(pkt)

state

DERIVED CLASS
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

45

Constructor Constructor: Creat Creating ng an Object

OT l Example OTcl: E l

Invocation

Object instantiation Return the value stored in the instvar state


46

Set the instvar state to be 0

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

Invoke the instproc move

OT l Main OTcl: M i Characteristics Ch i i


Declaration Anywhere Constructor = init Destructor = destroy y Call through object or class Instvar $self = itself Instproc next: call the same instproc of the mother class

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

47

OT l Syntax OTcl: S
Class Declaration
Class <classname> [-superclass <Baseclassname>]

Instvar declaration: Declared in an instproc


$self instvar <name1> <name2>

Instvar access: set


Retrieve the value: Set the value:
$<object> set <instvar_name> <value> $<object> j set <instvar_name>

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

48

OT l Syntax OTcl: S
Instproc declaration
<classname> instproc <proc_name> {<arg1> <argn>} { <body> }

Note: <argi> can be replaced with { {<argi> i <def>} d f }, where <def> d f is the default value, automatically assigned if the value is not specified at the invocation.
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

49

OT l Syntax OTcl: S
Instproc invocation
<object> <proc_name> <val1> <valn>

Object construction
OTcl: <classname> <object <object_name> name> NS2: new <classname>

new does d t two thi things


alloc{}: Allocate memory init{}: Necessary initialization
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

50

OT l Useful OTcl: U f l Procedures P d


next:

Invoke the instproc (with the same name) of the base class.
$self next [<args>]

info: i f R Return t th the information i f ti of f


Instvar: <varname> info <options>

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

51

OT l Useful OTcl: U f l Procedures P d


info: Return the information of Class: <classname> info <options>

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

52

OT l Useful OTcl: U f l Procedures P d


class:

Change the class init: Constructor instvar: Declare an instvar instproc: Declare an instproc next: Invoke instproc of the mother class proc: Declare l a procedure set: Set or return the value of an instvar unset: t The opposite of set unknown: Invoked when no matched instproc superclass: Define the superclass
53

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

OT l Useful OTcl: U f l Procedures P d


More on procedure pertaining to
Class: Visit
ftp://ftp tns lcs mit edu/pub/otcl/doc/class html ftp://ftp.tns.lcs.mit.edu/pub/otcl/doc/class.html

Object: Visit
ftp://ftp.tns.lcs.mit.edu/pub/otcl/doc/object.html

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

54

Outline
Tcl/Otcl
Tcl Regular Expression OTcl

Unix Essentials

Summary y

Basic Command Grep p AWK

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

55

U i B Unix: Basic i commands d


Basic Commands
ls more/less cd mv pwd cp chmod rm

Redirection
Pipe Pi (|): ) a | b Use input of a as an input of b Write Redirection (>) : a > b.txt Write output of a in the file b.txt Append Redirection (>>): a >> b.txt Append outputof a to the file b.txt
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

56

U i G Unix: Grep
Look for a <pattern> through a set of files
grep [option] <pattern> [<filename>]

<pattern> can be either text or regular

p expression

Most frequently q y used


grep -r <pattern> * Look for a <pattern> in all sub-directory r = recursive
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

57

Outline
Tcl/Otcl
Tcl Regular Expression OTcl

Unix Essentials

Summary y

Redirection Command Grep p AWK

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

58

AWK Overview AWK: O i


Developed by Aho Aho, Weinberger, Weinberger and Kernighan (thus AWK) awk gawk (gnu extenstion) Main Ma n purpose purpose: Extract words from a structured file
Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

59

AWK Example AWK: E l


Input: infile.txt infile txt

Output: Lines with EnQ

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

60

AWK Syntax AWK: S


Invocation

Tell AWK what what to do do!! !!

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

61

R Records d and d Fi Fields ld


A Record = A line in a data file Fields
Within Withi a record d Separated by delimiter

A delimiter
A white space by default

Modified by -F option E.g., E g -F: F: Use : as a delimiter


Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

62

E Examples l
Record = Entire Line Delimiter D li i = Whi White space Fields (stored in variables)
$1 = EnQ $2 = 0.164 $3 = FromNode

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

63

AWK Script S i
Syntax

Key steps

1. Do <initialization> 1 2. For each record If <pattern> is matched, do <actions> 3. Do <final actions>


64

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

Patterns
Recall: Th Three types of f patterns: 1. Empty: p y Match everything y g 2. Regular expression: Enclosed by // 3. Boolean: ==, >, <, >=, <=
65

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

P Pattern: Examples E l
AWK script:
BEGIN{print Begin Program;} /EnQ/ {print Found EnQ;} /DeQ/ {print Found DeQ;} if $2 > 0.17 {print $2;} END{print {p End Program;} g ;}

Output:
Begin Program Found EnQ Found DeQ Found EnQ Found DeQ Q Found EnQ 0.172 Found DeQ 0.172 F Found d E EnQ Q 0.178 0 178 End Program

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

66

A i Actions
A statement ends with ; Basic Actions
+ * / (addition) (subtraction) (multiplication) (division) ++ (increment) -- (decrement) = (assignment) % (modulo)

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

67

A i Actions: O Output
Basic printing:
print <item1> <item2>

Print with a specified format:


printf(<format>,<item1>,<item2> )

Write to a file (>):


print test > myfile.txt

Append App nd to t a file fil (>>):


print test >> myfile.txt

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

68

E Example l
Input: infile.txt infile txt Show lines with EnQ

>> awk /EnQ/ infile.txt

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

69

V i bl Variables
No Declaration Type: Floating point or String A i Assign: U Use = Every y text is variable, unless Enclosed by String Enclosed by [] [ ] Array Enclosed by [] Associative Array
70

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

C Control l Structure S
Main Structures: If, If While While, for

Breaking keywords

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

71

Outline
Tcl/Otcl
Tcl Regular Expression OTcl

Unix Essentials

Summary y

Redirection Command Grep p AWK

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

72

Summary
Tcl Interpreter C++ Compiler Q: Main difference? Pros and Cons ? Regular expression Pattern matching OTcl = Object oriented version of Tcl Unix basic commands Redirection commands: |, >, >> Grep: Pattern finding command AWK: Extract info based on given pattern

Textbook: T. Issariyakul and E. Hossain, Introduction to Network Simulator NS2, Springer 2008.

73

You might also like