Programming Using Tcl/Tk Week 2 Seree Chinodom

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

CSCI 6962: Server-side Design and Programming Input Validation and Error Handling.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
The Web Warrior Guide to Web Design Technologies
 2005 Pearson Education, Inc. All rights reserved Introduction.
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.
CSCI 4550/8556 Computer Networks Comer, Chapter 3: Network Programming and Applications.
 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
Guide To UNIX Using Linux Third Edition
Introduction to C Programming
Introduction to Unix (CA263) Introduction to Shell Script Programming By Tariq Ibn Aziz.
Javascript and the Web Whys and Hows of Javascript.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Innovation Intelligence ® 1 Chapter 1: Introduction to TCL.
Imperative Programming
Introduction to Shell Script Programming
1 Operating Systems Lecture 3 Shell Scripts. 2 Shell Programming 1.Shell scripts must be marked as executable: chmod a+x myScript 2. Use # to start a.
1 Operating Systems Lecture 3 Shell Scripts. 2 Brief review of unix1.txt n Glob Construct (metacharacters) and other special characters F ?, *, [] F Ex.
Java: Chapter 1 Computer Systems Computer Programming II.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
The UNIX Shell. The Shell Program that constantly runs at terminal after a user has logged in. Prompts the user and waits for user input. Interprets command.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
Introduction to Bash Programming Ellen Zhang. Previous three classes What have we learnt so far ?
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
Tcl/TK Tutorial. 2 Learning Tcl/TK What is Tcl/TK? –An interpreted programming language Build on-the-fly commands, procedures Platform-independent Easy.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Introduction to Perl Yupu Liang cbio at MSKCC
Chapter 9: Perl Programming Practical Extraction and Report Language Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
JavaScript, Fourth Edition
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
9-Nov-97Tri-Ada '971 TASH An Alternative to the Windows API TRI-Ada ‘97 Terry J. Westley
TCL TK. Tcl/Tk C functions can become Tcl commands that are invoked interactively Tk = scriptable, portable user interface –Windows, X (Unix), MacOS,
Dongsoo S. Kim  Tcl: Tool Command Language Interpreted programming (scripting) language Build on-the-fly commands and procedures Embeddable.
Week Four Agenda Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems Upcoming deadlines.
Introduction to Programming with Tcl. Introduction Using two languages  C++ for “ data ”  Otcl for control Tcl has been widely used as a scripting language.
Scripting.
CS 403: Programming Languages Lecture 20 Fall 2003 Department of Computer Science University of Alabama Joel Jones.
Perl Subroutines User Input Perl on linux Forks and Pipes.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Week Four Agenda Announcements Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
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.
CS 330 Class 7 Comments on Exam Programming plan for today:
Chapter 8: Control Structures
Programming Using Tcl Maxwell Created By: Quan Nguyen Created Date: 12/12/2016 TCL Training1.
TCL/TK Tool Command Language/Tool Kit.
What is Bash Shell Scripting?
NS-2 LAB: TCL Miriam Allalouf Semester A.
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
PHP.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
CSE 303 Concepts and Tools for Software Development
CSE 303 Concepts and Tools for Software Development
Introduction to Bash Programming, part 3
Exceptions and networking
Presentation transcript:

Programming Using Tcl/Tk Week 2 Seree Chinodom

What We'll Do Today u Tell me about yourselves u Review Tcl syntax from last week u Expressions u Lists u Strings and pattern matching u Control structures u Procedures u Error handling u File and network I/O and process management u Getting info at runtime

Who you are u Write on a piece of paper: –Your name –What you do –What you want to do with Tcl/Tk –Primary platform you use (UNIX, Wintel, Mac?) –What other computer languages you know –Anything you’d especially like to see covered

Summary of Tcl Command Syntax u Command: words separated by whitespace u First word is a function, others are arguments u Only functions apply meanings to arguments u Single-pass tokenizing and substitution u $ causes variable interpolation u [ ] causes command interpolation u “” prevents word breaks u { } prevents all interpolation u \ escapes special characters u TCL HAS NO GRAMMAR!

More On Substitutions  Keep substitutions simple: use commands like format for complex arguments.  Use eval for another level of expansion: exec rm *.o ํ *.o: No such file or directory glob *.o ํ a.o b.o exec rm [glob *.o] ํ a.o b.o: No such file or directory eval exec rm [glob *.o]

Tcl Expressions u C-like (int and double) u Command, variable substitution occurs within expressions.  Used in expr, if, other commands. Sample commandResult set b 55 expr ($b*4) expr $b <= 20 expr $a * cos(2*$b) expr {$b * [fac 4]}120 u Tcl will promote integers to reals when needed u All values translated to the same type  Note that expr knows about types, not Tcl!

Tcl Arrays u 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 u 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!)

Tcl Expressions u What’s happening in these expressions? expr $a * cos(2*$b) $a, $b substituted by scanner before expr is called expr {$b * [fac 4]}120 here, $b is substituted by expr itself u Therefore, expressions get substituted more than once! set b \$a set a 4 expr $b * 28

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

Lists u Zero or more elements separated by white space: red green blue u Braces and backslashes for grouping: a b {c d e} f (4 words) one\ word two three (3 words) u List-related commands: concatlindexllengthlsearch foreachlinsertlrangelsort lappendlistlreplace  Note: all indices start with 0. end means last element u Examples: lindex {a b {c d e} f} 2 ํ c d e lsort {red green blue} ํ blue green red

Lists are Powerful u A list makes a handy stack Sample commandResult set stack 11 push stack redred 1 push stack {a fish}{a fish} red 1 pop stacka fish (stack is now red 1)  push and pop are very short and use list commands to do their work

More about Lists u 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 u Commands and lists are closely related –A command is a list –Use eval to evaluate a list as a command

Commands And Lists: Quoting Hell u Lists parse cleanly as commands: each element becomes one word. u To create commands safely, use list commands: button.b -text Reset -command {set x $initValue} ( initValue read when button invoked)... -command "set x $initValue" (fails if initValue is " New York ": command is " set x New York ")... -command "set x {$initValue}" (fails if initValue is " { ": command is " set x {{} ")... -command [list set x $initValue] (always works: if initValue is " { " command is " set x \{ ") u List commands do all the work for you!

String Manipulation u String manipulation commands: regexpformatsplitstring regsubscanjoin  string subcommands compare first last index length match range toupper tolower trim trimleft trimright  Note: all indexes start with 0. end means last char

Globbing & Regular Expressions u "Globbing" - a simple pattern language –* means any sequence of characters –? matches any one character –[chars] matches and one character in chars –\c matches c, even if c is *, [, ?, etc. u Good for filename matching –*.exe, [A-E]*.txt, \?*.bak  glob command applies a glob pattern to filenames foreach f [glob *.exe] { puts "$f is a program" }

Globbing & Regular Expressions u "Regular Expressions" are a powerful pattern language –. (period) matches any character –^ matches start of a string –$ matches end of a string –\x single character escape –[chars] matches any of chars. ^: not. -: range. –(regexp) matches the regexp –* matches 0 or more of the preceding –+ matches 1 or more of the preceding –? matches 0 or 1 or the preceding –| can be used to divide alternatives.

Globbing & Regular Expressions u Examples: [A-Za-z0-9_]+ : valid Tcl identifiers T(cl|k) : Tcl or Tk  regexp command regexp T(cl|k) "I mention Tk" w t => returns 1 (match), w becomes "Tk", t gets "k" u regsub command regsub -nocase perl "I love Perl" Tcl mantra => returns 1 (match), mantra gets "I love Tcl" regsub -nocase {Where's ([a-z]*)\?} \ "Where's Bob?"{Who's \1?} result => returns 1 (match), result gets "Who's Bob?"

The format and scan Commands  format does string formatting. format "I know %d Tcl commands" 97 => I know 97 Tcl commands –has most of printf's capabilities –can also be use to create complex command strings  scan is like scanf set x "SSN#: # " scan $x "SSN#: %d" ssn puts "The social security number is $ssn" => The social security number is

Control Structures u C-like in appearance. u Just commands that take Tcl scripts as arguments. u 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 } u Commands: ifforswitchbreak foreachwhileevalcontinue source

Control Structure Examples u if expr script u for script expr script script for {set i 0} {$i<10} {incr i} {... u switch (opt) string {p1 s1 p2 s2...} foreach name $my_name_list { switch -regexp $name { ^Pete* {incr pete_count} ^Bob|^Robert {incr bob_count} default {incr other_count} }

More on Control Structures u Brackets are never required - so watch out! set x 3 if $x>2 {... <= this is OK, eval’ed once while $x>2 {... <= this is NOT OK, eval’ed many times! set a {red blue green} foreach i $a <= this is OK foreach I red blue green {... NOT OK!  foreach [array names A] is a common idiom

Procedures  proc command defines a procedure: proc sub1 x {expr $x-1} u Procedures behave just like built-in commands: sub1 3 ํ 2 u Arguments can have default values: proc decr {x {y 1}} { expr $x-$y } name list of argument names body

Procedures and Scope u 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 > proc deltax {d} { global x set x [expr $x-$d] } > deltax 1 => 9

Procedures and Scope  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 u level naming: (NOTE: Book is wrong (p. 84)) –#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  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 u Variable-length argument lists: proc sum args { set s 0 foreach i $args { incr s $i } return $s } sum ํ 15 sum ํ 0

Errors u Errors normally abort commands in progress, application displays error message: set n 0 foreach i { } { 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  Global variable errorCode holds machine-readable information about errors (e.g. UNIX errno value). NONE (in this case) u 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 +" u You can generate errors yourself (style question:) error "bad argument" return -code error "bad argument"

Tcl File I/O u Tcl file I/O commands: opengetsseekflushglob closereadtellcd fconfigure fblocked fileevent putssourceeofpwdfilename u File commands use 'tokens' to refer to files set f [open "myfile.txt" "r"] => file4 puts $f "Write this text into file" close $f

Tcl File I/O u gets and puts are line oriented set x [gets $f] reads one line of $f into x  read can read specific numbers of bytes read $f 100 => (up to 100 bytes of file $f)  seek, tell, and read can do random-access I/O set f [open "database" "r"] seek $f 1024 read $f 100 => (bytes of file $f)

Tcl File I/O  fileevent lets you watch a file set f [open log r] fileevent $f readable \ {set data [read $f]; puts $f} u Doesn't seem to work right on Windows NT, others?  fblocked, fconfigure give you control over files fconfigure -buffering [line|full] fconfigure -blocking [true|false] fconfigure -translation [auto|binary|cr|lf|crlf] fblocked returns boolean

TCP, Ports, and Sockets u Networking uses layers of abstractions –In reality, there is current on a wire... u The Internet uses the TCP/IP protocol u Abstractions: –IP Addresses ( ) –Port numbers (80 for WWW, 25 for SMTP) u Sockets are built on top of TCP/IP u Abstraction: –Listening on a port for connections –Contacting a port on some machine for service u Tcl provides a simplified Socket library

Tcl Network I/O  socket creates a network connection set f [socket 80] fconfigure $f -buffering line puts $f "GET /" puts [read $f] => loads of HTML from Sun's home page u Network looks just like a file! u To create a server socket, just use socket -server accept portno

I/O and Processes  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 u Command line arguments –argc is count, argv0 is interp name, argv is list of args u Tcl/Tk version –tcl_version, tk_version (7.5, 4.1) u Platform-specific information –tk_platform array –osVersion, machine, platform, os –3.51, intel, windows, Windows NT on my box

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 therfore replace any built-in command

Some More Interesting Tcl Features u Autoloading: – unknown invoked when command doesn't exist. –Loads Tcl procedures on demand from libraries. –Uses search path of directories.  load Tcl command –Long awaited standard interface for dynamic loading of Tcl commands from DLLs,.so's, etc.  interp Tcl command –You can create multiple independent Tcl interpreters in one process –interp -safe creates Safe-Tcl (sandbox) interpreters

Tcl 7.6 and Tk 4.2 u Major revision of grid geometry manager, needed for SpecTcl code generator (GUI builder)  C API change for channel (I/O) drivers (eliminate Tcl_File usage). u No other changes except bug fixes. u Now in beta release; final release in late September.

For Next Week... u Programming assignment #1: –Write a program which accepts, from a file or the keyboard, a list of programmers and the programming languages they know…: Barbara Modern: C++, Java, Eiffel Sam Slowpoke: FORTRAN IV, JPL –… and produces a report of languages and their users: C++: Barbara Modern, Tom Teriffic FORTRAN IV: Sam Slowpoke –Be sure to use procedures to modularize your program, and don't hard-code the names of any languages!

For Next Week... u Programming assignment #1 u Try to check out the Netscape Plug-in  Buy the reader and find pages about commands introduced since Ousterhout was published: fileevent, socket, fconfigure, interp, others... u Read Chapters 6 through 13 and 15 of Ousterhout