Programming Using TclTk Week 2 - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

Programming Using TclTk Week 2

Description:

Review Tcl syntax from last week. Expressions. Lists. Strings and pattern matching ... red fish blue fish = list. red $fish blue $fish = not a list, but ... – PowerPoint PPT presentation

Number of Views:106
Avg rating:3.0/5.0
Slides: 41
Provided by: johno202
Category:

less

Transcript and Presenter's Notes

Title: Programming Using TclTk Week 2


1
Programming Using Tcl/TkWeek 2
  • Dr. Ernest J. Friedman-Hill
  • ejfried_at_herzberg.ca.sandia.gov
  • http//herzberg.ca.sandia.gov/

2
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

3
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 youd especially like to see covered

4
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!

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
  • C-like (int and double)
  • Command, variable substitution occurs within
    expressions.
  • Used in expr, if, other commands.
  • Sample command Result
  • set b 5 5
  • expr (b4) - 3 17
  • expr b lt 2 0
  • expr a cos(2b) -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!

7
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
  • gt fred 2
  • You can 'fake' 2-D arrays
  • set A(1,1) 10
  • set A(1,2) 11
  • array names A
  • gt 1,1 1,2 (commas included in names!)

8
Tcl Expressions
  • Whats happening in these expressions?
  • expr a cos(2b) -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 \a
  • set a 4
  • expr b 2 8

9
Tcl String Expressions
  • Some Tcl operators work on strings too
  • set a Bill Bill
  • expr a lt "Anne" 0
  • lt, gt, lt, gt, , and ! work on strings
  • Beware when strings can look like numbers
  • You can also use the string compare function

10
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
  • Examples
  • lindex a b c d e f 2 ? c d e
  • lsort red green blue ? blue green red

11
Lists are Powerful
  • 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 is now red 1)
  • push and pop are very short and use list commands
    to do their work

12
More about Lists
  • A true lists meaning wont change when
    (re)scanned
  • red animal blue animal lt not a listred fish
    blue fish lt list
  • red \fish blue \fish lt not a list, but
  • list red \fish blue \fish gives you
  • red fish blue fish lt which is a list
  • 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
  • Lists parse cleanly as commands each element
    becomesone 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!

14
String Manipulation
  • String manipulation commands
  • regexp format split string
  • regsub scan join
  • 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
  • "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"

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

17
Globbing Regular Expressions
  • Examples
  • A-Za-z0-9_ valid Tcl identifiers
  • T(clk) Tcl or Tk
  • regexp command
  • regexp T(clk) "I mention Tk" w t
  • gt returns 1 (match), w becomes "Tk", t gets "k"
  • regsub command
  • regsub -nocase perl "I love Perl" Tcl mantra
  • gt returns 1 (match), mantra gets "I love Tcl"
  • regsub -nocase Where's (a-z)\? \
  • "Where's Bob? Who's \1? result
  • gt 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
  • gt 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"
  • gt The social security number is 148766207

19
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 - 1while i
    gt 0 lappend b lindex a i incr i
    -1
  • Commands
  • if for switch break
  • foreach while eval continue
  • source

20
Control Structure Examples
  • if expr script
  • for script expr script script
  • for set i 0 ilt10 incr i ...
  • switch (opt) string p1 s1 p2 s2...
  • foreach name my_name_list
  • switch -regexp name
  • Pete incr pete_count
  • BobRobert incr bob_count
  • default incr other_count

21
More on Control Structures
  • Brackets are never required - so watch out!
  • set x 3
  • if xgt2 ... lt this is OK, evaled once
  • while xgt2 ... lt this is NOT OK, evaled

  • many times!
  • set a red blue green
  • foreach i a lt this is OK
  • foreach i red blue green ...

  • NOT OK!
  • foreach i array names A is a common idiom

22
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
body
list of argument names
23
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
  • gt set x 10
  • gt proc deltax d
  • set x expr x-d
  • gt deltax 1 gt can't read x no such variable
  • gt proc deltax d
  • global x
  • set x expr x-d
  • gt deltax 1 gt 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
  • 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 var1

25
Procedures and Scope
  • uplevel does for code what upvar does for
    variables
  • proc loop from to script
  • set i from
  • while i lt to
  • uplevel script
  • incr i
  • set s ""
  • loop 1 5 set s s
  • puts s gt

26
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
  • ? 15
  • sum? 0

27
Errors
  • Errors normally abort commands in progress,
    application displays error message
  • set n 0foreach i 1 2 3 4 5 set n expr
    n ii? syntax error in expression "n
    ii"
  • Global variable errorInfo provides stack trace
  • set errorInfo? syntax error in expression "n
    ii" while executing"expr n ii"
    invoked from within"set n expr n ii..."
    ("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)
  • Can intercept errors (like exception handling)
  • catch expr 2 msg? 1 (catch returns 0OK,
    1err, other values...)
  • set msg? syntax error in expression "2 "
  • You can generate errors yourself (style
    question)
  • error "bad argument"
  • return -code error "bad argument"

29
Tcl File I/O
  • Tcl file I/O commands
  • open gets seek flush globclose read tell cd fcon
    figure fblocked fileeventputs source eof pwd fi
    lename
  • File commands use 'tokens' to refer to files
  • set f open "myfile.txt" "r"
  • gt file4
  • puts f "Write this text into file"
  • close f

30
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
  • gt (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
  • gt (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
  • Doesn't seem to work right on Windows NT, others?
  • fblocked, fconfigure give you control over files
  • fconfigure -buffering linefull
  • fconfigure -blocking truefalse
  • fconfigure -translation autobinarycrlfcrlf
  • fblocked returns boolean

32
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

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
  • gt 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

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

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

39
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!

40
For Next Week...
  • Programming assignment 1
  • 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
Write a Comment
User Comments (0)
About PowerShow.com