NS-2 LAB: TCL Miriam Allalouf 2005-2006 - Semester A.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Introduction to C Programming
Programming Using Tcl/Tk These slides are based upon u several Tcl/Tk text books u material byDr. Ernest J. Friedman-Hill.
CS Lecture 03 Outline Sed and awk from previous lecture Writing simple bash script Assignment 1 discussion 1CS 311 Operating SystemsLecture 03.
NS-2 LAB: TCL Semester A Miriam Allalouf.
Writing Tcl Scripts (cont.) Outline –Variable Scoping –Strings –Eval –File/Channel I/O –Processes –System Info –Errors –Reflection/Debugging –Libraries.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Tcl/TK Tutorial Fan Yang Kristy Hollingshead
Writing Tcl Scripts Outline Goal Reading Syntax Data Types
Guide To UNIX Using Linux Third Edition
Guide To UNIX Using Linux Third Edition
XP Tutorial 1 New Perspectives on JavaScript, Comprehensive1 Introducing JavaScript Hiding Addresses from Spammers.
Introduction to C Programming
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
Innovation Intelligence ® 1 Chapter 1: Introduction to TCL.
Introduction to Shell Script Programming
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
Tcl/TK Tutorial. 2 Learning Tcl/TK What is Tcl/TK? –An interpreted programming language Build on-the-fly commands, procedures Platform-independent Easy.
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Introduction to Perl Yupu Liang cbio at MSKCC
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Programming Using Tcl/Tk Week 2 Seree Chinodom
TCL TK. Tcl/Tk C functions can become Tcl commands that are invoked interactively Tk = scriptable, portable user interface –Windows, X (Unix), MacOS,
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
Dongsoo S. Kim  Tcl: Tool Command Language Interpreted programming (scripting) language Build on-the-fly commands and procedures Embeddable.
Scripting.
Introduction to Javascript. What is javascript?  The most popular web scripting language in the world  Used to produce rich thin client web applications.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
An Introduction To Tcl Scripting John Ousterhout Sun Microsystems Laboratories Tcl/Tk Tutorial, Part II.
TCL/TK Tool Command Language/Tool Kit. What is TCL? u Tool Command Language u An interpreted programming language  Created by John Ousterhout.John Ousterhout.
COMP075 OS2 Bash Scripting. Scripting? BASH provides access to OS functions, like any OS shell Also like any OS shell, BASH includes the ability to write.
Information and Computer Sciences University of Hawaii, Manoa
Definition of the Programming Language CPRL
More about comments Review Single Line Comments The # sign is for comments. A comment is a line of text that Python won’t try to run as code. Its just.
Programming what is C++
CS 330 Class 7 Comments on Exam Programming plan for today:
Department of Computer Engineering
Bash Introduction (adapted from chapters 1 and 2 of bash Cookbook by Albing, Vossing, & Newham) CPTE 440 John Beckett.
Learning to Program D is for Digital.
Introduction Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
Pamela Moore & Zenia Bahorski
Shell Scripting March 1st, 2004 Class Meeting 7.
JavaScript Syntax and Semantics
Statement atoms The 'atomic' components of a statement are: delimiters (indents, semicolons, etc.); keywords (built into the language); identifiers (names.
Functions CIS 40 – Introduction to Programming in Python
4. Javascript Pemrograman Web I Program Studi Teknik Informatika
CSE 303 Concepts and Tools for Software Development
Server-Side Application and Data Management IT IS 3105 (Spring 2010)
Chapter 8: Control Structures
Programming Using Tcl Maxwell Created By: Quan Nguyen Created Date: 12/12/2016 TCL Training1.
Intro to PHP & Variables
TCL/TK Tool Command Language/Tool Kit.
IPC144 Introduction to Programming Using C Week 1 – Lesson 2
Chapter 10 Programming Fundamentals with JavaScript
INFO/CSE 100, Spring 2005 Fluency in Information Technology
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
INFO/CSE 100, Spring 2006 Fluency in Information Technology
Creating your first C program
Programming Fundamentals Lecture #3 Overview of Computer Programming
Adapted from slides by Nicholas Shahan and Dan Grossman
Python Primer 1: Types and Operators
CSE 303 Concepts and Tools for Software Development
CSE 303 Concepts and Tools for Software Development
Introduction to Bash Programming, part 3
CIS 136 Building Mobile Apps
LING/C SC/PSYC 438/538 Lecture 4 Sandiway Fong.
Presentation transcript:

NS-2 LAB: TCL Miriam Allalouf 2005-2006 - Semester A

Why Scripting languages? TCL Introduction Why Scripting languages? C,C++,Java  Perl, Python, TCL UNIX scripting languages: XTERM + shell, PERL: based around C type language constructs. Scripting languages chars.: Configure Glue different application Flexible data structure  easy porting Slow but processor’s power grew! Undefined variable types Code and Data are the same : easy to add code!

Scripting languages TCL Introduction A script file is a list of commands which a shell interpreter reads and executes. First line is a line which indicates what interpreter to run. Rest of the file is just a sequence of commands, most often just like those you can run on your command line. Script languages include some method for manipulating variables and data.

Script languages – TCL TCL Introduction The tcl interpreter gives a bridging solutions: TK - display extension for using X widgets (TCL/TK) XML CORBA ORACLE, Sybase DCOM,SAP,WEB, HTTP SNMP Test Equipment The tcl interpreter is called "tclsh". You can run: which tclsh in order to find out where your tcl interpreter is located. The first line of your tclsh script should be: #!/your.location/tclsh

TCL - Tool Command Language - History TCL Introduction TCL - Tool Command Language - History 1980’s Tcl invented by John Ousterhout while working on design tools for integrated circuits at the University of California at Berkeley. Wanted a language that could be used over many tools. To create a good interpreted language To build it as a library package that could be reused in many different applications. To provide a language interpreter with a set of generic facilities, such as variables, control structures, and procedures. To enable the application that used the language to extend it and add its own features into the language, so that the language could be used to control the application.

TCL/Tk: Tk was ready by the end of 1990. TCL Introduction TCL Goals The goals set for the language were: The language must be extensible: The language must be very easy to work on, and it should be easy and convenient to add features to the language in order to adapt this language to the programmer’s specific goal. The application should be very simple and generic: The application should be able to work easily with many different applications in such a way that it does not restrict the features that those applications have to provide. Integration: The language should be able to glue together the extensions. Thus the language must have good facilities for integration. The first version of Tcl in a graphical text editor was ready by the spring of 1988. TCL/Tk: Tk was ready by the end of 1990.

TCL Plan: Review Tcl syntax Expressions Lists, arrays TCL Introduction TCL Plan: Review Tcl syntax Expressions Lists, arrays Strings and pattern matching Control structures Procedures Error handling File and network I/O and process management Getting info at runtime

Tcl script (String based) = TCL Introduction TCL Basics Tcl script (String based) = Sequence of commands. Commands separated by newlines, semi-colons. Tcl command = One or more words separated by white space. First word is command name, others are arguments. Returns string result (always returns – usually numbers) Examples: set a 22 set the variable ‘a’ to 22 puts "Hello, World!" world’s shortest program expr 100 + 20 Calculates the sum of 100 and 20 and results the result, which is 120

Division Of Responsibility TCL Introduction Division Of Responsibility Chops commands into words. Makes substitutions. Does not interpret values of words. Single pass operation! Command Tcl Parser Words Interprets words. Can invoke parser recursively. Produces string result. Command Procedure Result

Tcl: Tool Command Language TCL Introduction Tcl: Tool Command Language Simple syntax (similar to sh, C, Lisp): set a 47 í 47 Substitutions: set b $a í 47 set b [expr $a+10] í 57 Quoting: set b "a is $a" í a is 47 set b {[expr $a+10]} í [expr $a+10]

Variable Substitution TCL Introduction Variable Substitution Syntax: $varName Variable name is letters, digits, underscores. This is a little white lie, actually. Tcl will promote integers to reals when needed All values translated to the same type Note that expr knows about types, not Tcl! May occur anywhere in a word. Sample command Result set b 66 66 set a b b set a $b 66 set a $b+$b+$b 66+66+66 set a $b.3 66.3 set a $b4 no such variable

Command Substitution Syntax: [script] TCL Introduction Command Substitution Syntax: [script] Evaluate script, substitute result. May occur anywhere within a word. Sample command Result set b 8 8 set a [expr $b+2] 10 set a "b-3 is [expr $b-3]" b-3 is 5

TCL expression TCL Introduction What’s happening in these expressions? expr $a * cos(2*$b)  -5.03443 $a, $b substituted by scanner before expr is called expr {$b * [fac 4]}  120 here, $b is substituted by expr itself Therefore, expressions get substituted more than once! (In fact, TCL once, and expr once) set b \$a set a 4 expr $b * 2  8

Tcl String Expressions Some Tcl operators work on strings too TCL Introduction Tcl String Expressions Some Tcl operators work on strings too set a Bill Bill expr {$a < "Anne"} 0 <, >, <=, >=, ==, and != work on strings Beware when strings can look like numbers You can also use the string compare function

Controlling Word Structure TCL Introduction Controlling Word Structure Words break at white space and semi-colons, except: Double quotation marks group words as a single argument to a command and prevent breaks.Dollar signs and square brackets are interpreted inside double quotation marks. set a "x is $x; y is $y" Curly braces also group words into a single argument. In this case, however, elements within the braces are not interpreted or substituted. set a {[expr $b*$c]} Backslashes quote special characters: For example, \n generates a newline. set a word\ with\ \$\ and\ space Backslashes can escape newline (continuation) Substitutions don't change word structure: set a "two words" set b $a

Notes on Substitution and Parsing TCL Introduction Notes on Substitution and Parsing Tcl substitution rules are simple and absolute Example: comments set a 22; set b 33 <- OK # this is a comment <- OK set a 22 # same thing? <- Wrong! set a 22 ;# same thing <- OK Parser looks at a command just once! It’s OK to experiment Expressions exist that can’t be written in one command Sometimes things get hairy “{[“cmd”]}”

Tcl Commands: TCL Introduction Built-in commands: this group of commands is provided by the Tcl interpreter itself. All of the commands discussed so far. Present in all Tcl applications. Tcl extension commands: created using the Tcl extension mechanism. Tcl APIs to create a new command where the command procedure is implemented in C or C++, command name be registered with the Tcl interpreter. TCL recognizes this particular name for a Tcl command and, will execute the new command. proc commands: consists of procedures created with the proc command.

Zero or more elements separated by white space: TCL Introduction Lists Zero or more elements separated by white space: red green blue Braces and backslashes for grouping: a b {c d e} f (4 words) one\ word two three (3 words) List-related commands: concat lindex llength lsearch foreach linsert lrange lsort lappend list lreplace Note: all indices start with 0. end means last element Concat ? List list …? 合併成一個 Lappend 新增 Lindex 得到第幾個 Linsert 插入list從第幾個 Llength 算個數 Lrange 取出一部分 List 形成list

Lists are Powerful TCL Introduction Examples: lindex {a b {c d e} f} 2 > c d e lsort {red green blue} > blue green red A list makes a handy stack Sample command Result set stack 1 1 push stack red red 1 push stack {a fish} {a fish} red 1 pop stack a fish (stack contains: red 1) push and pop are very short and use list commands to do their work 抽考 寫寫看

More about Lists TCL Introduction A true list’s meaning won’t change when (re)scanned red $animal blue $animal <= not a list red fish blue fish <= list red \$fish blue \$fish <= not a list, but list red \$fish blue \$fish gives you… red {$fish} blue {$fish} <= which is a list Commands and lists are closely related A command is a list Use eval to evaluate a list as a command

String Manipulation TCL Introduction string subcommands compare first last index length match range toupper tolower trim trimleft trimright Note: all indexes start with 0. end means last char

Tcl Arrays TCL Introduction Tcl arrays are 'associative arrays': index is any string set x(fred) 44 set x(2) [expr $x(fred) + 6] array names x => fred 2 You can 'fake' 2-D arrays: set A(1,1) 10 set A(1,2) 11 array names A => 1,1 1,2 (commas included in names!)

Control Structures TCL Introduction C-like in appearance. Just commands that take Tcl scripts as arguments. Example: list reversal. Set list b to reverse of list a: set b "" set i [expr [llength $a] - 1] while {$i >= 0} { lappend b [lindex $a $i] incr i -1 } Commands: if for switch break foreach while eval continue source

Control Structure Examples TCL Introduction Control Structure Examples if expr script for script expr script script for {set i 0} {$i<10} {incr i} {...} switch (opt) string {p1 s1 p2 s2...} foreach index [array names a] { puts $a($index) }

More on Control Structures TCL Introduction More on Control Structures Brackets are not required set x 3 if $x>2 {... <= this is OK, eval’ed once while $x>2 {... <= eval’ed many times! set a {red blue green} foreach i $a <= this is OK foreach i red blue green {... NOT OK! foreach index [array names A] is a common idiom

proc command defines a procedure: TCL Introduction Procedures proc command defines a procedure: proc sub1 x {expr $x-1} Procedures behave just like built-in commands: sub1 3 í 2 Arguments can have default values: proc decr {x {y 1}} { expr $x-$y } Return value of a procedure is implicitly the return value of the last statement in the script. Unless the ‘return’ command exists. name body list of argument names

Procedures and Scope TCL Introduction 抽考 Hanoi Tower Scoping: local and global variables. Interpreter knows variables by their name and scope Each procedure introduces a new scope global procedure makes a global variable local > set x 10 > proc deltax {d} { set x [expr $x-$d] } > deltax 1 => can't read x: no such variable global x > deltax 1 => 9 抽考 Hanoi Tower

Procedures and Scope TCL Introduction Note that global is an ordinary command proc tricky {varname} { global $varname set $varname "passing by reference" upvar and uplevel let you do more complex things level naming: #num: #0 is global, #1 is one call deep, #2 is 2… num: 0 is current, 1 is caller, 2 is caller's caller… proc incr {varname} { upvar 1 $varname var set var [expr $var+1] }

Procedures and Scope TCL Introduction uplevel does for code what upvar does for variables proc loop {from to script} { set i $from while {$i <= $to} { uplevel $script incr i } set s "" loop 1 5 {set s $s*} puts $s => *****

More about Procedures TCL Introduction Variable-length argument lists: proc sum args { set s 0 foreach i $args { incr s $i } return $s } sum 1 2 3 4 5 >> 15 sum >> 0

ERRORS TCL Introduction Errors normally abort commands in progress, application displays error message: set n 0 foreach i {1 2 3 4 5} { set n [expr {$n + i*i}] } í syntax error in expression "$n + i*i" Global variable errorInfo provides stack trace: set errorInfo í syntax error in expression "$n + i*i" while executing "expr {$n + i*i}" invoked from within "set n [expr {$n + i*i}]..." ("foreach" body line 2) ...

Advanced Error Handling TCL Introduction Advanced Error Handling Global variable errorCode holds machine-readable information about errors (e.g. UNIX errno value). NONE (in this case) Can intercept errors (like exception handling): catch {expr {2 +}} msg í 1 (catch returns 0=OK, 1=err, other values...) set msg í syntax error in expression "2 +" You can generate errors yourself (style question:) error "bad argument" return -code error "bad argument"

Tcl file I/O Tcl file I/O commands: TCL Introduction Tcl file I/O Tcl file I/O commands: open gets seek flush glob close read tell cd fconfigure fblocked fileevent puts source eof pwd filename File commands use 'tokens' to refer to files set f [open "myfile.txt" "r"]  file4 puts $f "Write this text into file" close $f

TCP, Ports, and Sockets : Tcl Network I/O TCL Introduction TCP, Ports, and Sockets : Tcl Network I/O Tcl provides a simplified Socket library socket creates a network connection set f [socket www.sun.com 80] fconfigure $f -buffering line puts $f "GET /" puts [read $f] => loads of HTML from Sun's home page Network looks just like a file! To create a server socket, just use socket -server accept portno

I/O and Processes TCL Introduction exec starts processes, and can use '&' set FAVORITE_EDITOR emacs exec $FAVORITE_EDITOR & no filename expansion; use glob instead eval exec "ls [glob *.c]" you can open pipes using open set f [open "|grep foo bar.tcl" "r"] while {[eof $f] != 0} { puts [gets $f] }

Runtime Information Facilities The info command TCL Introduction Runtime Information Facilities The info command what variables are there? info vars, info globals, info locals, info exists what procedures have I defined, and how? info procs, info args, info default, info body, info commands the rename command can rename any command, even built-in can therefore replace any built-in command

NS-2 lab TCL Introduction Resources Bibliography: The Tcl/Tk track is based  on Ousterhout and Welch's book (Practical Programming in Tcl/Tk). Online resources, some of the  most useful Tcl/Tk links:  http://dev.scriptics.com/man/tcl8.3/contents.htm Online Tcl/Tk manual pages: http://stage.caldera.com/Technology/tcl/Tcl.html A broad  list of Tcl/Tk resources. The Scriptics company (http://www.scriptics.com/)that commercializes Tcl and its developper web site. Tutorials: A  Tcl/Tk introduction The  TclTutor An online overview with examples. Tcl/Tk course material in hebrew (see the lecture notes section

NS-2 lab Introduction More Refernces http://www.ixiacom.com/products/paa/customappdev/ http://www.cetus-links.org/oo_tcl_tk.html#oo_tcl_tk_start_here http://www.pconline.com/~erc/tcl.htm http://www.scriptics.com/doc/scriptHistory.html http://www.itworld.com/AppDev/1243/UIR000804tk/ http://www.softpanorama.org/Scripting/tcl_tk.shtml http://www.tcl.tk/advocacy/choose.html http://www.cs.utah.edu/dept/old/texinfo/dejagnu/dejagnu_8.html http://www.usenix.org/publications/library/proceedings/tcl95/ http://216.239.51.100/search?q=cache:wTF3fij-gGQC:www.usenix.org/publications/library/proceedings/tcl97/full_papers/poster_bergeman/bergeman-abstract.pdf+tcl/tk+application+area&hl=en&ie=UTF-8