Download presentation
Presentation is loading. Please wait.
1
Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th http://lecture.compsci.buu.ac.th/TclTk
2
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
3
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
4
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!
5
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]
6
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) - 317 expr $b <= 20 expr $a * cos(2*$b)-5.03443 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!
7
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!)
8
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 * 28
9
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
10
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
11
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
12
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
13
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!
14
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
15
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" }
16
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.
17
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?"
18
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#: #148766207" scan $x "SSN#: %d" ssn puts "The social security number is $ssn" => The social security number is 148766207
19
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
20
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} }
21
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
22
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
23
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
24
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] }
25
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 => *****
26
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
27
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" 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)...
28
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"
29
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
30
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 1024-1123 of file $f)
31
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
32
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 (146.246.245.226) –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
33
Tcl Network I/O 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
34
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] }
35
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
36
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
37
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
38
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.
39
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!
40
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.