40
Programming Using Tcl/Tk Week 2 Seree Chinodom [email protected] http://lecture.compsci.buu.ac.th/ TclTk

Programming Using Tcl/Tk Week 2 Seree Chinodom [email protected]

Embed Size (px)

Citation preview

Page 1: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Programming Using Tcl/TkWeek 2

Seree Chinodom

[email protected]

http://lecture.compsci.buu.ac.th/TclTk

Page 2: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

What We'll Do Today

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

Page 3: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Who you are

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

Page 4: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Summary of Tcl Command Syntax

Command: words separated by whitespace 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 { } prevents all interpolation \ escapes special characters TCL HAS NO GRAMMAR!

Page 5: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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

[*. ]ํ a.o b.o: No such file or directory

*eval exec rm [glob .o]

Page 6: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Tcl Expressions C-like (int and double) Command, variable substitution occurs within expressions. Used in eeee, if, other commands.

Sample command Resultset b 5 5expr ($b*4) - 3 17expr $b <= 2 0expr $a * cos(2*$b) -5.03443expr {$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!

Page 7: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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

Page 8: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Tcl Expressions

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!

set b \$aset a 4expr $b * 2 8

Page 9: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Tcl String Expressions

Some Tcl operators work on strings too

set a Bill Billexpr {$a < "Anne"} 0

<, >, <=, >=, ==, and != work on strings

Beware when strings can look like numbers

You can also use the string compare function

Page 10: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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 lsearchforeach linsert lrange lsortlappend list lreplace

Note: all indices start with 0. end means last element Examples:

lindex {a b {c d e} f} 2 ํ c d elsort {red green blue} ํ blue green red

Page 11: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Lists are Powerful

A list makes a handy stack

Sample command Resultset stack 1 1push stack red red 1push stack {a fish} {a fish} red 1pop stack a fish (stack is now red 1)

push and pop are very short and use list commands to do their work

Page 12: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

More about Lists

A true list’s meaning won’t change when (re)scanned

red $animal blue $animal <= not a listred 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

Page 13: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Commands And Lists: Quoting Hell Lists parse cleanly as commands: each element becomes

one word. 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 \{")

List commands do all the work for you!

Page 14: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

String Manipulation

String manipulation commands:

regexp format split string

regsub scan join eeeeee subcommands

compare first last index length

match range toupper tolower trim

trimleft trimright Note: all indexes start with 0. end means last char

Page 15: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Globbing & Regular Expressions "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"

}

Page 16: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Globbing & Regular Expressions "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.

Page 17: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Globbing & Regular Expressions Examples:

[A-Za-z0-9_]+ : valid Tcl identifiers

T(cl|k) : Tcl or Tk regexp commandregexp T(cl|k) "I mention Tk" w t=> returns 1 (match), w becomes "Tk", t gets "k"

regsub commandregsub -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?"

Page 18: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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

Page 19: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Control Structures 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 breakforeach while eval continuesource

Page 20: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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 name $my_name_list {

switch -regexp $name {

^Pete* {incr pete_count}

^Bob|^Robert {incr bob_count}

default {incr other_count}

}

}

Page 21: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

More on Control Structures Brackets are never required - so watch out!

3set x

>2 {... <= this is OK, eval’ed once

>2 {... <= this is NOT OK, eval’ed

many times!

eeee eeee eeeeee{} foreach i $a <= this is OK

foreach I red blue green {...

NOT OK! foreach [array names A] is a common idiom

Page 22: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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}

name

list of argument names

body

Page 23: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Procedures and Scope 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

Page 24: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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 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]

}

Page 25: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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 => *****

Page 26: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

More about Procedures

Variable-length argument lists:proc sum args { set s 0 foreach i $args { incr s $i } return $s}

sum 1 2 3 4 5ํํํํํํํํํํํํํํ 15sumํ 0

Page 27: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Errors Errors normally abort commands in progress, applicati

on displays error message:set n 0foreach 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) ...

Page 28: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Advanced Error Handling

Global variable errorCode holds machine-readable information about errors (e.g. UNIX eeeee value).

NONE (in this case) Can intercept errors (like exception handling):

catch {expr {2 +}} msgํ 1 (catch returns 0=OK, 1=err, other values...)

eee eeeํ ee ee"2+"

You can generate errors yourself (style question:)

error "bad argument"

- return code error "bad argument"

Page 29: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Tcl File I/O

Tcl file I/O commands:

open gets seek flush globclose read tell cd

fconfigure fblocked fileeventputs 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

Page 30: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Tcl File I/O

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)

Page 31: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Tcl File I/O fileevent lets you watch a file

set f [open log r]

fileevent $f readable \

{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

Page 32: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

TCP, Ports, and Sockets Networking uses layers of abstractions

– In reality, there is current on a wire... The Internet uses the TCP/IP protocol Abstractions:

– IP Addresses (146.246.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

Page 33: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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

Network looks just like a file! To create a server socket, just use

socket -server accept portno

Page 34: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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]

}

Page 35: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Runtime Information Facilities

Command line arguments

– argc is count, argv0 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

– osVersion, machine, platform, os– 3.51, intel, windows, Windows NT on my box

Page 36: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

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

Page 37: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Some More Interesting Tcl Features Autoloading:

– unknow n 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

Page 38: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

Tcl 7.6 and Tk 4.2

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).

No other changes except bug fixes.

Now in beta release; final release in late September.

Page 39: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

For Next Week...

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!

Page 40: Programming Using Tcl/Tk Week 2 Seree Chinodom seree@buu.ac.th

For Next Week...

Programming assignment #1 Try to check out the Netscape Plug-in Buy the reader and find pages about commands introd

uced since Ousterhout was published: fileevent, socket, fconfigure, interp, others...

Read Chapters 6 through 13 and 15 of Ousterhout