550ed313e0942163c6052ce3d9e6ffb2.ppt
- Количество слайдов: 40
Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu. ac. th http: //lecture. compsci. buu. ac. th/Tcl. Tk
What We'll Do Today u Tell me about yourselves u Review Tcl syntax from last week Expressions Lists Strings and pattern matching Control structures Procedures u u u u Error handling File and network I/O and process management 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 Only functions apply meanings to arguments Single-pass tokenizing and substitution $causes variable interpolation [ ]causes command interpolation ”“prevents word breaks u u u u { }prevents all interpolation escapes special characters TCL HAS NO GRAMMAR!
More On Substitutions u u Keep substitutions simple: use commands like format for complex arguments. Use eval for another level of expansion: exec rm *. 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 command Result set b 5 5 expr ($b*4) - 3 17 expr $b <= 2 0 expr $a * cos(2*$b) -5. 03443 expr {$b * [fac 4]} 120 Tcl will promote integers to reals when needed All values translated to the same type Note that expr knows about types, not Tcl! u u
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, 2 1, 1 <=commas included in names(!
Tcl Expressions u 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 u Therefore, expressions get substituted more than once! set b $a set a 4 expr $b * 2 8
Tcl String Expressions u Some Tcl operators work on strings too set a Bill expr {$a < "Anne"} 0 u , == , =< , => , < , >and != work on strings u Beware when strings can look like numbers u 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: concat lindex llength foreach linsert lrange lappend list lreplace u u lsearch lsort Note: all indices start with 0. end means last element Examples: lindex {a b {c d e} f} 2 lsort {red green blue} red c d e blue green
Lists are Powerful u u A list makes a handy stack Sample command Result set stack 1 1 push stack red 1 push stack {a fish} red 1 pop stack a fish ) stack is now red 1( push and pop are very short and use list commands to do their work
More about Lists 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 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 u Lists parse cleanly as commands: each element becomes one word. To create commands safely, use list commands: button. b -text Reset -command {set x $init. Value} (init. Value read when button invoked( -. . . command "set x $init. Value" (fails if init. Value is "New York": command is "set x New York(" -. . . command "set x {$init. Value}" (fails if init. Value is "{": command is "set x("{}} -. . . command [list set x $init. Value] (always works: if init. Value is "{" command is "set x("} u List commands do all the work for you!
String Manipulation u String manipulation commands: regexp format split regsub scan join string u string subcommands compare first last index length match range toupper tolower trimleft trimright u Note: all indexes start with 0. end means last char
Globbing & Regular Expressions u u 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. 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-z 0 -9_]+ T(cl|k) : : valid Tcl identifiers 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"? u
The format and scan Commands u format does string formatting. format "I know %d Tcl commands" 97 <=I know 97 Tcl commands u – has most of printf's capabilities – can also be use to create complex command strings scan is like scanf set x "SSN#: #148766207" scan $x "SSN#: %d" ssn puts "The social security number is $ssn" <=The social security number is 148766207
Control Structures u C-like in appearance. u 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 { u u Commands: if foreach source switch while break eval continue
Control Structure Examples u if expr script for script expr script u for {set i 0} {$i<10} {incr i. . . } { switch (opt) string {p 1 s 1 p 2 s 2{. . . u 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 {. . . u <= 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 u proc command defines a procedure: proc sub 1 x {expr $x-1{ name body list of argument names u Procedures behave just like built-in commands: sub 1 3 2 u Arguments can have default values: proc decr {x {y 1} {{ expr $x-$y {
Procedures and Scope u 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 u Note that global is an ordinary command proc tricky {varname} { global $varname set $varname "passing by reference" u 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 u 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 1 2 3 4 5 15 sum 0
Errors u 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" u Global variable error. Info provides stack trace: set error. Info 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 u Global variable error. Code holds machine-readable information about errors (e. g. UNIX errno value. ( NONE u (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"+ u You can generate errors yourself (style question(: error "bad argument" return -code error "bad argument"
Tcl File I/O u u 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[" <=file 4 puts $f "Write this text into file" close $f
Tcl File I/O u u 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 1024 -1123 of file $f(
Tcl File I/O u fileevent lets you watch a file set f [open log r[ fileevent $f readable } u u set data [read $f]; puts $f{ 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 u u Networking uses layers of abstractions – In reality, there is current on a wire. . . The Internet uses the TCP/IP protocol Abstractions: – IP Addresses (146. 245. 226( – Port numbers (80 for WWW, 25 for SMTP( Sockets are built on top of TCP/IP Abstraction: – Listening on a port for connections – Contacting a port on some machine for service Tcl provides a simplified Socket library
Tcl Network I/O u 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 u Network looks just like a file! u To create a server socket, just use socket -server accept portno
I/O and Processes u exec starts processes, and can use'&' set FAVORITE_EDITOR emacs u u 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 u u Command line arguments – argc is count, argv 0 is interp name, argv is list of args Tcl/Tk version – tcl_version, tk_version (7. 5, 4. 1( Platform-specific information – tk_platform array – os. Version, machine, platform, os – , 3. 51 intel, windows, Windows NT on my box
Runtime Information Facilities u The info command what variables are there? – info vars, info globals, info locals, info exists u 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 u – Long awaited standard interface for dynamic loading of Tcl commands from DLLs, . so's, etc. interp Tcl command u – 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 Spec. Tcl code generator (GUI builder( u 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. . . Read Chapters 6 through 13 and 15 of Ousterhout u u
550ed313e0942163c6052ce3d9e6ffb2.ppt