Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Introduction

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

January 23, 2005 Slide 2 of 18


Introduction To Tcl/Tk - What’s Tcl/Tk? -

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/Tk major advantages:


• Simple and easy to learn syntax
• Ability to handle large enterprise-scale applications
• Ability to easy and quick creation of GUIs
• Tcl/Tk has a C API allows join compilation with the application C/C++
code to obtain single program executable
• It is open source - the distribution and using is completely free
• It is portable - the Tcl/Tk code is available and easy compilable on
virtually all known platforms - Unix - Solaris, AIX, HP, PC, MacOS etc.

• Tcl and Tk were created and developed by John Ousterhout, currently the CEO
of Scriptics Corporation (http://www.scriptics.com/).

January 23, 2005 Slide 3 of 18


Introduction To Tcl/Tk - Getting Started -

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

January 23, 2005 Slide 4 of 18


Introduction To Tcl/Tk - Tcl Scripting - Basics

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”

January 23, 2005 Slide 5 of 18


Introduction To Tcl/Tk - Tcl Scripting - Variable Substitution

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

January 23, 2005 Slide 6 of 18


Introduction To Tcl/Tk - Tcl Scripting - Controlling Word Structure

Controlling Word Structure


• Double-quotes prevent word breaks:
set x 1
set a “x = $x” ; # a is “x = 1”
• Curly braces prevent word breaks and variable/commands substitutions:
set a {x = $x} ; # a is “x = $x”
• Backslashes quote special characters:
set x Hello\ World\ ! ; # x is “Hello World!”
set y [string length \
$myString] ; # here \ quotes the newline

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

January 23, 2005 Slide 7 of 18


Introduction To Tcl/Tk - Tcl Scripting - Command Line Arguments

Command Line Arguments


• Predefined global variables argv and argc handle Tcl script command line
arguments
• argv is a list of all the command line arguments excluding the name of the
script itself
• argc is a number of the command line arguments
• argv0 stores the name of the script
puts "The program name is $argv0"
puts "Number of arguments: $argc”
set i 0
foreach arg $argv {
puts "Arg # $i: $arg"
incr i
}

January 23, 2005 Slide 8 of 18


Introduction To Tcl/Tk - Tcl Scripting - Math Expressions

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

January 23, 2005 Slide 9 of 18


Introduction To Tcl/Tk - Tcl Scripting - Control Structures

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

January 23, 2005 Slide 10 of 18


Introduction To Tcl/Tk - Tcl Scripting - Procedures

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

January 23, 2005 Slide 11 of 18


Introduction To Tcl/Tk - Tcl Scripting - Procedures

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

January 23, 2005 Slide 12 of 18


Introduction To Tcl/Tk - Tcl Scripting - Strings

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

January 23, 2005 Slide 13 of 18


Introduction To Tcl/Tk - Tcl Scripting - Lists

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}

January 23, 2005 Slide 14 of 18


Introduction To Tcl/Tk - Tcl Scripting - Arrays

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)”
}

January 23, 2005 Slide 15 of 18


Introduction To Tcl/Tk - Tcl Scripting - Error Handling

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”

January 23, 2005 Slide 16 of 18


Introduction To Tcl/Tk - Tcl Scripting - Files and Programs

Files and Programs


• exec command runs programs from Tcl script:
exec ls -alF
catch {exec sort -u myFile.tst} errMsg
• File I/O commands:
open gets puts read
tell seek eof flush
close
• file commands provides files manipulation commands - in a system indepen-
dent way:
file copy/delete/rename
file exists
file isfile/isdirectory
file atime/attributes/dirname/extension/mtime
file readable/writable
file type/pathtype
file size
file join
file owned
• exit terminates the current script

January 23, 2005 Slide 17 of 18


Introduction To Tcl/Tk - Tcl Scripting - Advanced Tcl Commands

Advanced Tcl Commands


• unset command deletes a variable:
unset x
puts $x ; # error! x doesn’t exist
• info exists command checks if a variable exists:
if {[info exists foo]} {
puts “foo = $foo”
}
• trace command monitors variable accesses:
trace variable myVar w {puts “myVar is changed!”}
trace variable foo r {puts “Somebody reads foo”}
• eval evaluates a Tcl script:
set cmd {puts stdout “Hello, World!”}
eval $cmd
• Opening a process pipeline:
set input [open “|sort /etc/passwd” r]
gets $input line
• Regular expressions handling: regexp and regsub commands
regsub -all {/} $unixPath {\\} dosPath
regexp {([^:]*):} $env(DISPLAY) match host

January 23, 2005 Slide 18 of 18

You might also like