Professional Documents
Culture Documents
Ganga
Ganga
To Tcl/Tk
Introduction To Tcl/Tk - Contents -
Contents
What’s Tcl/Tk? 3
Getting Started 4
Tcl Scripting 5
Basics 5
Variable Substitution 6
Command Substitution 6
Controlling Word Structure 7
Comment 7
Command Line Arguments 8
Math Expressions 9
Control Structures 10
Procedures 11
Procedures 12
Strings 13
Lists 14
Arrays 15
Error Handling 16
Files and Programs 17
Advanced Tcl Commands 18
What’s Tcl/Tk?
• Tcl (Tool Command Language) - high-level scripting language, can be used
as a stand-alone application or embedded in user application program
• Tk - graphical user interface toolkit built on top if Tcl, capable of rapid and sim-
ple creation of powerful and robust GUIs
• Tcl and Tk were created and developed by John Ousterhout, currently the CEO
of Scriptics Corporation (http://www.scriptics.com/).
Getting Started
• The main Tcl/Tk programs are tclsh and wish.
• tclsh (Tcl Shell) is a Tcl command interpreter
• wish (Windowing Shell) adds the graphical applications toolkit to the tcl shell.
• Starts a Tcl interpreter and prompts for a Tcl command. The commands are
entered interactively:
% set x 1
or run the Tcl code in file with the source command:
% source myExample.tcl
• On Unix one can create a standalone script:
#!/usr/local/bin/tclsh
puts “Hello, World!”
• On MS Windows you can add Tcl/Tk programs to Start menu using the com-
mand like:
“c:\Program Files\Tcl80\wish.exe” c:\mine\script.tcl
• Can be embedded in a C/C++ application
Tcl Scripting
Basics
• Tcl script = sequence of commands
• Commands are separated by newlines or semicolons (;)
• Tcl command = one or more words separated by a white space
• First word is a command name, others are arguments
• Always returns string result
• Examples:
set x 17; set y 67.3
puts $message
set myFileHandler [open “passwords.txt”]
• No variable declaration
• Single data type - string
• Different commands assign different meaning to their (string) arguments:
set a 15+10 ; # a is “15+10”
set y [expr 15+10] ; # y is “25”
string length “a b c d”
llength “a b c d”
Variable Substitution
• Syntax: $varName
• Variable name = sequence of letters, digits and underscores
• Occurs anywhere in a word:
set x 1 ; # x is 1
set y $x ; # y is 1
set z x ; # z is “x”
set a aa$x ; # a is “aa1”
set b aa$z ; # b is “aax”
set num 35$x.$x ; # num is 351.1
Command Substitution
• Syntax: [script]
• Evaluates script, substitutes result
• Occurs anywhere within a word:
set one 1
set ten [expr 9+$one]
set msg “ten equals [expr (21 - $one)/2]”
Comment
• # is a comment sign
• Must be at the beginning of a command:
# This is a comment
set x 1 # Wrong! not at the beginning of a command
set x 1 ; # Right
Math Expressions
• expr command evaluates math expressions
• Similar to C math syntax
• Supports boolean, integer and floating-point values
• Logical operations return either 1 (true) or 0 (false)
• Octal values are indicated by a leading zero: 033 is 27 decimal
• Hexadecimal values are indicated by 0x: 0xFF
• Supports scientific notation: 3.4e+10
• Has a number of built-in math functions - sin, cos, abs, pow, etc.
• Examples:
expr 64.2 / 2 ; 32.1
set allocLen [expr [string length $foo] + 5]
set pi [expr 2*asin(1.0)] ; 3.1415926535897931
set epsylon [expr .5*1e-10]
• Predefined variable tcl_precision sets the floating-point numbers precision:
expr 1 / 3.0 ; # 0.333333 - default 6 digits
set tcl_precision 17
expr 1 / 3.0 ; # 0.33333333333333331
Control Structures
• Just commands that take Tcl scripts as arguments
• C-like appearance
• Control structures commands
if for while foreach
switch break continue eval
• Example - list reversal:
set reversedList {}
set i [expr [llength $myList] - 1]
while {$i >= 0} {
lappend reversedList [lindex $myList $i]
incr i -1
}
• Example - factorial calculation:
set product 1
for {set i 1} {$i <= $x} {incr i} {
set product [expr $product * $i]
}
Procedures
• proc command defines a procedure:
proc <procName> <arg> <body>
• Example:
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c
}
• Procedures behave just like built-in commands:
puts "Diag(3, 4) = [Diag 3 4]"
• Always return string result
• Return the value of the last procedure statement or use return command
• Arguments can have default values:
proc decr {x {decrementor 1}} {
expr $x - $decrementor
}
set y 13
decr y ; # 12
decr y 7 ; # 6
Procedures
• Variable-length argument lists:
proc Sum args {
set sum 0
foreach arg $args {
incr sum $arg
}
return $sum
}
Sum 1 2 3 4 5 ; # 15
Sum 1.25 1.25 2.5 ; # 5
• Scoping: by default, all internal procedure variables are local.
• global command declares a variable as a global:
proc CircleLen { radius } {
global pi
expr 2*$pi*$radius
}
• Local variables shade globals
• upvar and uplevel commands define the scope from the calling stack
(dynamic scoping).
Strings
• Basic (only) data type in Tcl
• string command implements a collection of string operations:
string length <str>
string compare <str1> <str2>
string index <str> <index>
string tolower <str>
string toupper <str>
string match <pattern> <str>
etc.
• append command concatenates strings onto the given variable:
append foo a b c ; # foo = “abc”
set abc 7
append foo “ = “ $abc ; # foo = “abc = 7”
• format command formats a string according to a format specification
• scan command parses a string according to a format and assigns results to
variables
• string match does glob-style pattern matching:
string match a* alpha ; # 1
string match {[a-zA-Z0-9_]} $var
Lists
• Zero or more elements separated by white space
set list1 [list a b c 17 $var]
set list2 “a b c 17 $var”
• Braces and backslashes for grouping:
set myList {a b c {d e f}}
• Lots of list manipulation commands:
list lindex lappend llength
lsort lsearch lreplace lrange
linsert concat foreach
• Examples:
set new [list]
lappend new 1 2 ; # 1 2
lappend new “4 5” ; # 1 2 {4 5}
concat $new {6 7} a ; # 1 2 {4 5} 6 7 a
llength $new ; # 6
lindex $new 2 ; # {4 5}
lsearch $new 2 ; # 1
lsort -ascii {peach banana apple}
; # {apple banana peach}
Arrays
• An array is a variable with a string valued index:
set arr(index) 7
set x $arr(index) ; # x = 7
set arr($x,$y) $elem ; double indices
set arr(3, 7) ; ERROR!
set arr(3,\ 7) ; OK
• array names returns the list of the indices
• array size returns the number of indices
• array get returns a list of keys and values
• array set initializes an array from the given list
• Examples:
set fruits(apple) red
set fruits(banana) yellow
array names fruits ; # apple banana
array get fruits ; # apple red banana yellow
foreach key [array names fruits] {
puts “fruits($key) = $fruits($key)”
}
Error Handling
• Errors abort execution
• Global variable errorInfo provides stack trace
• catch command intercepts errors:
catch {expr 2*$a} errorMessage
set errorMessage
; # “can’t read "a": no such variable
• error command generates errors:
error “404: Unknown host”