Anda di halaman 1dari 32

An Introduction To Tcl Scripting

Michael Miller
msmiller@acm.org
Introduction
◆ Component technologies:
– Tcl: embeddable scripting language
– Tk: GUI toolkit and widgets based on Tcl.

◆ The principle: universal scripting language controls


everything: functions, interfaces, communication.

◆ Results:
– Raise the level of X programming: simpler, 5-10x
faster application development.
– Greater power: more things programmable,
applications work together.
– Active objects: replace data with scripts.
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 2
Outline
◆ Tcl scripting language.
◆ Tk toolkit.
◆ Extending Tcl with C.
◆ Survey of applications and extensions.
◆ Conclusions.

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 3


Tcl: Tool Command Language

◆ Interactive programs need command languages:


– Typically redone for each application.
– Result: weak, quirky.
• emacs and csh powerful, but can't reuse.

◆ Solution: reusable scripting language.


– Interpreter is a C library.
– Provides basic features: variables, procedures, etc.
– Applications extend with additional features.

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 4


Scripting Language Philosophy
∞ Program size, complexity, reuse 1

◆ Large, complex applications: ◆ Interactive commands, scripting:


– Performance important. – Performance less important.
– Need structure. – Minimum structure: less
– Goal: prevent bad things. overhead, easy interchange.
– Goal: enable good things.

One language can't meet all needs?


Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 5
Two-Language Approach
∞ Program size, complexity, reuse 1

C Tcl

◆ Use Tcl for scripting, C or C++ for large things.


◆ Goals for Tcl:
– Minimal syntax: easy to learn and type.
– Minimal structure: make things play together.
– Simple interfaces to C: extensibility.

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 6


Embedding Tcl In Applications
◆ Application generates scripts. Tcl Application
◆ Tcl parses scripts, passes words Init
to command procedures.
◆ Application extends built-in Parser
Command
Loop
command set:
– Define new object types in C.
– Implement primitive operations
as new Tcl commands.
– Build complex features with Tcl Built-In Application
Commands Commands
scripts.

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 7


Extensions
Extension Tcl Application
Init

Command
Parser Loop

Extension Built-In Application


Commands Commands Commands

◆ Extensions can be developed independently:


– Network communication, database access, security, ...
◆ Applications can include combinations of extensions.
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 8
Tcl: Tool Command Language
◆ Simple syntax (similar to sh, C, Lisp):
set a 47 47
◆ Substitutions:
set b $a 47
set b [expr $a+10] 57
◆ Quoting:
set b "a is $a" a is 47
set b {[expr $a+10]} [expr $a+10]

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 9


More On The Tcl Language
◆ Rich set of built-in commands:
– Variables, associative arrays, lists.
– C-like expressions.
– Conditionals, looping:
if "$x < 3" {
puts "x is too small"
}
– Procedures.
– Access to TCP/IP sockets, files, subprocesses.
◆ Only representation is strings:
– Easy access from C.
– Programs and data interchangeable.
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 10
Language Overview
◆ Two parts to learning Tcl:
◆ 1. Syntax and substitution rules:
– Substitutions simple, but may be confusing at first.
◆ 2. Built-in commands:
– Can learn individually as needed.
– Control structures are commands, not language syntax.

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 11


Basics
◆ Tcl script =
– Sequence of commands.
– Commands separated by newlines, semi-colons.
◆ Tcl command =
– One or more words separated by white space.
– First word is command name, others are arguments.
– Returns string result.
◆ Examples:
• set a 22; set b 33
• set a 22
set b 33

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 12


Division Of Responsibility
Command
◆ Chops commands into words.
Tcl Parser ◆ Makes substitutions.
◆ Does not interpret values of words.

Words

◆ Interprets words.
Command Procedure
◆ Produces string result.

Result
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 13
Arguments
◆ Parser assigns no meaning to arguments (quoting by
default, evaluation is special):
C: x = 4; y = x+10
y is 14
Tcl: set x 4; set y x+10
y is "x+10"
◆ Different commands assign different meanings to their
arguments:
set a 122
expr 24/3.2
eval "set a 122"
button .b -text Hello -fg red
string length Abracadabra
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 14
Variable Substitution
◆ Syntax: $varName
◆ Variable name is letters, digits, underscores.
◆ May occur anywhere in a word.
Sample command Result
set b 66 66
set a b b
set a $b 66
set a $b+$b+$b 66+66+66
set a $b.3 66.3
set a $b4 no such variable

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 15


Command Substitution
◆ Syntax: [script]
◆ Evaluate script, substitute result.
◆ May occur anywhere within a word.

Sample command Result


set b 8 8
set a [expr $b+2] 10
set a "b-3 is [expr $b-3]" b-3 is 5

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 16


Controlling Word Structure
◆ Words break at white space and semi-colons, except:
– Double-quotes prevent breaks:
set a "x is $x; y is $y"
– Curly braces prevent breaks and substitutions:
set a {[expr $b*$c]}
– Backslashes quote special characters:
set a word\ with\ \$\ and\ space

◆ Substitutions don't change word structure:


set a "two words"
set b $a
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 17
Expressions
◆ C-like (int and double), extra support for string operations.
◆ Command, variable substitution occurs within expressions.
◆ Used in expr, other commands.
Sample command Result
set b 5 5
incr b -1 4
expr ($b*4) - 3 17
expr $b <= 2 0
expr $a * cos(2*$b) -5.03443
expr {$b * [fac 4]} 120
set a Bill Bill
expr {$a < "Anne"} 0
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 18
Lists
◆ Zero or more elements separated by white space:
red green blue
◆ Braces and backslashes for grouping:
a b {c d e} f
◆ List-related commands:
concat lindex llength lsearch
foreach linsert lrange lsort
lappend list lreplace
◆ Examples:
lindex {a b {c d e} f} 2 c d e
lsort {red green blue} blue green red
◆ Useful with eval and foreach.
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 19
Control Structures
◆ C-like appearance.
◆ Just commands that take Tcl scripts as arguments.
◆ Example: list reversal.
set b ""
set i [expr [llength $a] - 1]
while {$i >= 0} {
lappend b [lindex $a $i]
incr i -1
}
◆ Commands:
if for switch break
foreach while eval continue
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 20
Procedures
◆ proc command defines a procedure:
proc sub1 x {expr $x-1}
name body
list of argument names
◆ Procedures behave just like built-in commands:
sub1 3 2
◆ Arguments can have defaults:
proc decr {x {y 1}} {
expr $x-$y
}
◆ Scoping: local and global variables.
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 21
Procedures, cont'd
◆ 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
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 22
Errors
◆ 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)
...
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 23
Advanced Error Handling
◆ Can intercept errors:
catch {expr {2 +}} msg
1
set msg
syntax error in expression "2 +"
◆ Can generate errors:
error "bad argument"
◆ Global variable errorCode holds machine-readable
information about errors (e.g. UNIX errno value).

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 24


Additional Tcl Features:
◆ String manipulation commands:
regexp format split string binary
regsub scan join append
◆ Example of regexp
proc printurl {url} {
set urlmatch {([^:]+)://([^:/]+)(:([0-9]+))?(/.*)}
regexp $urlmatch $url match protocol server x port path
puts "url = $match"
puts "protocol = $protocol"
puts "server = $server"
puts "port = $port"
puts "path = $path"
}
printurl http://www.sun.com:80/index.html

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 25


Additional Tcl Features, cont'd
◆ File I/O commands:
open gets seek flushglob
file pid
close read tell cd
puts source eof pwd
◆ Subprocesses with exec command:
catch {exec grep foo << $input | wc} error

◆ Variable scoping:
global uplevel upvar
◆ Access to Tcl internals:
info rename trace
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 26
Arrays (or Tcl records)
proc init_array {arr} {
upvar $arr REC
set nv "owner user file test"
for {set i 1} { $i <= 3} {incr i} {
set x [format "%03d" $i]
foreach {name value} $nv {set REC($x,$name) $value$i}
}
}
proc show_array {arr} {
upvar $arr REC
set text "records ="
set curr 000
foreach rec [lsort [array names REC]] {
set i [string first , $rec]
set x [string range $rec 0 [expr $i-1]]
set n [string range $rec [expr $i+1] end]
if {$x != $curr} { set curr $x ; puts "" ; append text " $x" }
puts "rec $x $n = $REC($rec)"
}
puts $text
}
init_array RECORD
show_array RECORD

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 27


Advanced Tcl Features

◆ Autoloading:
– unknown procedure invoked when command doesn't
exist.
– Loads procedures on demand from libraries.
– Uses search path of directories.
◆ Others (Tcl 7.5+):
– Dynamic loading of binaries: load command.
– Security: Safe-Tcl, namespaces.
– Event-driven I/O.
– Socket support.
Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 28
Advanced Tcl Features, cont'd
◆ trace:
– Follow reading/writing of tcl variables.
◆ vwait:
– Moved tk event loop to tcl.
– Useful for TCP/IP server programs
vwait forever
◆ upvar and uplevel:
– Can be used to build new commands.
– Ease access to globals and other scopes.

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 29


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/Tk Tutorial: Tcl Scripting August 4, 1997 slide 30
Commands And Lists: Quoting
◆ 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 \{")

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 31


Tcl Syntax Summary
◆ Script = commands separated by newlines or
semicolons.
◆ Command = words separated by white space.
◆ $ causes variable substitution.
◆ [] causes command substitution.
◆ "" quotes white space and semi-colons.
◆ {} quotes all special characters.
◆ \ quotes next character, provides C-like substitutions.
◆ # for comments (must be at beginning of command).

Tcl/Tk Tutorial: Tcl Scripting August 4, 1997 slide 32

Anda mungkin juga menyukai