TCL (Tool Command Language)
TCL (Tool Command Language)
* Introduction & Expectations * Pre Test * Tcl Theory Session - 1 * Break - 1 * Lab Session - 1 * Tcl Theory Session - 2 * Lunch Break * Lab Session - 2 * Tcl Theory Session - 3 * Break - 2 * Lab Session - 3
Tcl/Tk Training 20/10/2004 1
Objective
The objective of the training is to provide the user: ? A basic familiarity with the syntax,features used in language so as to enable them to write scripts using the Tcl/Tk.
Tcl/Tk Training
20/10/2004
Prerequisite
The prerequisite for the course is familiarity with any high level programming language
Tcl/Tk Training
20/10/2004
History
Tcl/Tk Training
20/10/2004
Overview
* Tcl stands for Tool Command Language
* Tcl is open source so it's completely free. * Tk is a graphical user interface toolkit to
create powerful GUIs
Tcl/Tk Training 20/10/2004 6
Overview (Contd..)
Tcl/Tk Training
20/10/2004
Contents
General
* Why scripting language * Why Tcl/Tk * Comparision with other programming languages * What is not covered * References
Tcl/Tk Training
20/10/2004
Contents Contd. . . . .
Tcl
* How to start Tcl * Puts - For text output * Comments * Variables * Command substitution * Expressions * Predefined variables * Control flow * Procedures * Global & upvar * Lists and its functions with foreach loop
Tcl/Tk Training
20/10/2004
Contents Contd. . . . .
* String Manipulations * Regular expressions * Arrays * File Operations * Use of exec,info * Built in commands eval, upvar,uplevel * Errors & Exception Handling * Command line arguments
Tcl/Tk Training
20/10/2004
10
Contents Contd. . . . .
Tk
* Relation Between Tcl & Tk * Labels, Text Boxes, Buttons * Check Boxes, Radio Buttons * List Boxes * Scroll Bars * Menus * Geometry Manager(Packer) * Events Handling
Tcl/Tk Training
20/10/2004
11
* The application does a lot of string processing. * It must be easy to extend and customize the application * System programming languages are ideal for building basic
components and applications from scratch
* Scripting
languages work well for integrating components and applications into larger applications
Tcl/Tk Training
20/10/2004
12
Why Tcl&Tk ?
* Simplicity * Graphical User Interfaces * Internationalization * Extensibility * Embeddability * Easy debugging * Regular expression support
Tcl/Tk Training
20/10/2004
13
Features
Visual Basic
Rapid development
?
Great regular expressions Easily extensible
Embeddable
Easy GUIs
Internationalization support
? ?
14
Tcl/Tk Training
20/10/2004
15
References
Books:
* Tcl and the Tk Toolkit by John K. Ousterhout * Practical Programming in Tcl and Tk by
Brent Welch
Internet resources:
Tcl/Tk Training
20/10/2004
16
Tcl/Tk Training
20/10/2004
17
? Tcl shell works much like the other shells .. ? Tcl shell takes the command from the user and pass them
to the Tcl interpreter
use exit
20/10/2004
18
Text Output
? The command to output a string in Tcl is
the 'puts' command EXAMPLE 1. % puts Hello Hello %
Tcl/Tk Training
20/10/2004
19
Comments
? Use # to mark a line as comment ? Use ;# to comment after the command string
EXAMPLE 3. % puts "Hello World " ;# This is comment Hello World % puts "Hello World;" #This is comment wrong # args: should be "puts ?-nonewline? ?channelId? string" % puts "Hello World"; Hello World % #This is comment
Tcl/Tk Training 20/10/2004 21
Variables
Variables (Contd..)
? ?
If varName consists only of alphanumeric characters, and no parenthese, it is a scalar variable. Set returns the value of the variable
EXAMPLE 5 % ;# Assign a number to variable Y % set Y 1.24 1.24 % % ;# Display the contents of Y % puts $Y 1.24 %
Tcl/Tk Training 20/10/2004 23
Variables (Contd..)
% set x(pk) CRD CRD % puts $x(pk) CRD % set x(dk) IPDF IPDF % puts $x(pk) $x(dk) can not find channel named "CRD" % puts "$x(pk) $x(dk)" CRD IPDF %
Tcl/Tk Training 20/10/2004 24
EXAMPLE 6
EXAMPLE 7.
% ;# Just puts a divider % puts "..............................." ............................... % % ;# More than one item can be put in a single puts % set label "The value in Y is: " The value in Y is: % puts "$label $Y" The value in Y is: 1.24 %
Tcl/Tk Training
20/10/2004
25
? The evaluation of a command is done in 2 phases. ? Grouping words within double quotes allows
The first phase is a single pass of substitutions. The second phase is the evaluation of the resulting command
substitutions to occur within the quotations. The substituted group is then evaluated as a single argument EXAMPLE 8. % set Z "Albany" Albany % set Z_LABEL "The Capitol of New York is: " The Capitol of New York is: % puts "$Z_LABEL $Z" The Capitol of New York is: Albany
Tcl/Tk Training 20/10/2004 26
\a ............. Audible alert (Bell) .....................\x07 \b ............. Backspace ....................................\x08 \f .............. Form Feed (Clear screen) ......\x0c \n ............. New Line ......................................\x0a \r ..............Carriage Return ..........................\x0d \t ...........Tab ................................................\x09 \v ...........Vertical Tab .................................\x0b \xhh ......... .Hex value ......................................h = 0-9,A-F,a-f EXAMPLE 10. % ;# The next line needs a backslash to escape the '$' % puts "\nBen Franklin is on the \$100.00 bill" Ben Franklin is on the $100.00 bill
Tcl/Tk Training 20/10/2004 28
EXAMPLE 11. % puts "This string comes out\ on a single line" This string comes out on a single line
Tcl/Tk Training
20/10/2004
29
EXAMPLE 12
% set a 100.00 100.00 % puts "Washington is not on the $a bill" ;# This is not what you want Washington is not on the 100.00 bill % puts "Lincoln is not on the $$a bill" ;# This is OK Lincoln is not on the $100.00 bill % puts "Hamilton is not on the \$a bill" ;# This is not what you want Hamilton is not on the $a bill % puts "Ben Franklin is on the \$$a bill" ;# But, this is OK Ben Franklin is on the $100.00 bill % puts "Tab\tTab\tTab" Tab Tab Tab
Tcl/Tk Training 20/10/2004 30
Tcl/Tk Training
20/10/2004
33
Tcl/Tk Training
20/10/2004
34
% set z {[set x "This is a string within quotes within braces"]} [set x "This is a string within quotes within braces"] % puts "Note the curly braces: $z\n" Note the curly braces: [set x "This is a string within quotes within braces"] % set a "[set x {This is a string within braces within quotes}]" This is a string within braces within quotes % puts "See how the set is executed: $a" See how the set is executed: This is a string within braces within quotes
Tcl/Tk Training 20/10/2004 35
expr arg ?arg arg ...? ? Concatenates arg's, evaluates the result as a Tcl expression, and returns the value.
? Valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16. ? If no numeric interpretation is possible, then an operand
is left as a string
Tcl/Tk Training
20/10/2004
38
EXAMPLE 18.
% set a 3 3 % set b 6 6 % expr 3.1 + $a 6.1 % expr 2+"$a.$b" 5.6 % expr 4 * [llength "6 2"] 8
Tcl/Tk Training
20/10/2004
39
EXAMPLE 20. % expr $a + {5.33} 10.33 % expr $a + [set b 4.5] 9.5 % expr $a + int([set b 4.5]) 9
Tcl/Tk Training 20/10/2004 41
Tcl/Tk Training
20/10/2004
42
Tcl/Tk Training
20/10/2004
43
abs(arg)
EXAMPLE 23.
expr 5 / 4 returns 1 expr 5 / 4.0 , expr 5 / ( [string length "abcd"] + 0.0 ) both return 1.25. expr 20.0/5.0 returns 4.0, not 4. STRING OPERATIONS expr {"0x03" > "2"} will return 1.
Tcl/Tk Training
20/10/2004
46
Switch
? switch - Evaluate one of several scripts,
depending on a given value switch ?options? string pattern body ?pattern body ...? switch ?options? string {pattern body ?pattern body ...?} ? The following options are currently supported: -exact -regexp EXAMPLE 24. Eg. switch abc a - b {format 1} abc {format 2} default {format 3} will return 2,
Tcl/Tk Training 20/10/2004 47
if - Execute scripts conditionally if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN? ? The then and else arguments are optional EXAMPLE 26. % set x 1; 1 % if {$x != 1} { puts "$x is != 1" } else { puts "$x is 1" } 1 is 1
Tcl/Tk Training 20/10/2004 49
If-else
While
? while - Execute script repeatedly as long as a condition is met ? while test body
EXAMPLE 27. set x 0 while {$x<10} { puts "x is $x" incr x }
For
? for - For loop ? for start test next body
EXAMPLE 28. for {set x 0} {$x<10} {incr x} { puts "x is $x" }
Tcl/Tk Training
20/10/2004
51
? proc - Create a Tcl procedure ? proc name args body ? The proc command creates a new Tcl procedure
named name
Procedures
Procedures (Contd..)
? Args is a list of arguments which will be passed to name. ? When proc is invoked, local variables with these names will
be created,and the values to be passed to proc will be copied to the local variables.
? Body is a body of code to execute when proc is called. ? The value that a proc returns can be defined with the
return command.
EXAMPLE 30.
% proc for {a b c} { puts "The for command has been replaced by a puts"; puts "The arguments were: $a\n$b\n$c\n" } % % for {set i 1} {$i < 10} {incr i} The for command has been replaced by a puts The arguments were: set i 1 $i < 10 incr i %
Tcl/Tk Training 20/10/2004 54
Procedures (Contd..)
? A proc can have variable number of arguments. ? An argument can also be defined to have a default value. ? Variables can be defined with a default value by placing
the variable name and the default within braces within args
EXAMPLE 32.
proc example {first {second ""} args} { if {$second == ""} { puts "There is only one argument and it is: $first"; return 1; } else { if {$args == ""} { puts "There are two arguments - $first and $second"; return 2; } else { puts "There are many arguments - $first and $second and $args"; return "many"; } } }
Tcl/Tk Training 20/10/2004 56
Tcl/Tk Training
20/10/2004
57
EXAMPLE 33.
% ;# An example of Upvar % proc SetPositive {variable value } { upvar $variable myvar; if {$value < 0} { set myvar [expr -$value];} else {set myvar $value;} return $myvar; } % % SetPositive x 5; 5 % SetPositive y -5; 5 % % puts "X : $x Y: $y\n" X : 5 Y: 5
Tcl/Tk Training 20/10/2004 58
List
A list is simply an ordered collection of numbers, words, strings, etc.
? set lst {{item 1} {item 2} {item 3}} ? set lst [split "item 1.item 2.item 3" "."] ? set lst [list "item 1" "item 2" "item 3"] ? lindex list index returns the index'th item from the list.
The first item is 0 EXAMPLE 34. % set x "a b c" abc % puts "Item 2 of the list {$x} is: [lindex $x 2]\n" Item 2 of the list {a b c} is: c
Tcl/Tk Training 20/10/2004 59
List (Contd..)
? llength returns the number of elements in a list.
EXAMPLE 35. % set y [split 7/4/1776 "/"] 7 4 1776 % llength $y 3 % set y [split 7/4/1776 "/"] 7 4 1776 % puts "We celebrate on the [lindex $y 1]'th day of the [lindex $y 0]'th month\n " We celebrate on the 4'th day of the 7'th month
Tcl/Tk Training 20/10/2004 60
Foreach
? foreach varname list body ? Foreach will execute the body code one time for each list
item in list.
On each pass, varname will contain the value of the next list item.
Tcl/Tk Training
20/10/2004
61
Foreach (Contd..)
EXAMPLE 36. % set x "a b c" abc % set i 0; 0 % foreach j $x { puts "$j is item number $i in list x" incr i; } a is item number 0 in list x b is item number 1 in list x c is item number 2 in list x
Tcl/Tk Training 20/10/2004 62
Manipulating List
? Concat ? lappend
EXAMPLE 37. % set a [concat a b {c d e} {f {g h}}] a b c d e f {g h} % puts "Concated: $a\n" Concated: a b c d e f {g h} % lappend a {ij K lm} ;# Note: {ij K lm} is a single element a b c d e f {g h} {ij K lm} % puts "After lappending: $a\n" After lappending: a b c d e f {g h} {ij K lm}
Tcl/Tk Training 20/10/2004 63
EXAMPLE 38.
?linsert
% set b [linsert $a 3 "1 2 3"] ;# "1 2 3" is a single element a b c {1 2 3} d e f {g h} {ij K lm} % % puts "After linsert at position 3: $b\n" After linsert at position 3: a b c {1 2 3} d e f {g h} {ij K lm}
Tcl/Tk Training
20/10/2004
64
EXAMPLE 39.
?lreplace
% ;# "AA" and "BB" are two list elements. % set b [lreplace $b 3 5 "AA" "BB"] a b c AA BB f {g h} {ij K lm} % % puts "After lreplacing 3 positions with 2 values at position 3: $b\n" After lreplacing 3 positions with 2 values at position 3: a b c AA BB f {g h} { i j K lm}
Tcl/Tk Training
20/10/2004
65
List (Contd..)
? lsearch list pattern
searches list for an entry that matches pattern, and returns the index for the first match, or a -1 if there is no match.
? lsort list
sorts list and returns a new list in the sorted order. By default, it sorts the list into alphabetic order.
Tcl/Tk Training
20/10/2004
66
EXAMPLE 40.
% set list [list {Washington 1789} {Adams 1797} {Jefferson 1801} \ {Madison 1809} {Monroe 1817} {Adams 1825} ] {Washington 1789} {Adams 1797} {Jefferson 1801} {Madison 1809} {Monroe 1817} {Adams 1825} % set x [lsearch $list Washington*]; 0 % set y [lsearch $list Madison*]; 3 % % incr x; incr y -1; ;# Set range to be not-inclusive 2 % % set subsetlist [lrange $list $x $y] {Adams 1797} {Jefferson 1801}
Tcl/Tk Training 20/10/2004 67
Strings
? string length string ? Returns the length of string ? string index string index ?Returns the char at the index'th position in string
EXAMPLE 41. % set string "this is my test string" this is my test string % puts "There are [string length $string] characters in \"$string\"" There are 22 characters in "this is my test string" % puts "[string index $string 1] is the second character in \"$string\"" h is the second character in "this is my test string"
Tcl/Tk Training 20/10/2004 68
EXAMPLE 42.
?string range string first last ? Returns a string composed of the characters from
first to last
% set string "this is my test string" this is my test string % % puts "\"[string range $string 5 10]\" are characters between the 5'th and 10'th" "is my " are characters between the 5'th and 10'th
Tcl/Tk Training
20/10/2004
69
Strings (Contd..)
? There are 6 string subcommands that do pattern and
string matching. string compare string1 string2 returns -1 ..... If string1 is less than string2 0 ........ If string1 is equal to string2 1 ........ If string1 is greater than string2
Tcl/Tk Training
20/10/2004
70
Tcl/Tk Training
20/10/2004
71
? string first string1 string2 ? string last string1 string2 ? string match pattern string ? string tolower string ? string toupper string ? string trim string ?trimChars? ? string trimleft string ?trimChars? ? format formatString ?arg1 arg2 ...
Tcl/Tk Training
20/10/2004
72
Regular expressions
% set sample "Where there is a will, There is a way." Where there is a will, There is a way. % set result [regexp {[a-z]+} $sample match] 1 % puts "Result: $result match: $match" Result: 1 match: here
Tcl/Tk Training 20/10/2004 73
Tcl/Tk Training
20/10/2004
75
Arrays
Arrays (Contd..)
EXAMPLE 46. % array set array1 [list {123} {Abigail Aardvark} \ {234} {Bob Baboon} \ {345} {Cathy Coyote} \ {456} {Daniel Dog} ] % % puts "Array1 has [array size array1] entries\n" Array1 has 4 entries % % puts "Array1 has the following entries: \n [array names array1] \n" Array1 has the following entries: 345 234 123 456
Tcl/Tk Training 20/10/2004 77
File access
? FileName is the name of the file to open. ? access is the file access mode ? r......Open the file for reading. The file must already exist. ? r+Open the file for reading and writing. The file
must already exist.
Create the file if it doesn't exist, or set the length to zero if it does exist Create the file if it doesn't exist, or set the length to zero if it does exist.
20/10/2004 78
? close fileID Closes a file previously opened with open ? gets fileID ?varName? Reads a line of input from FileID,
and discards the terminating newline.
Tcl/Tk Training
20/10/2004
80
Tcl/Tk Training
12/09/2002
Tcl/Tk Training
12/09/2002
Files (Contd..)
EXAMPLE 3. % set ail1 [glob C:/windows/w*.dll] C:/windows/WINSOCK.DLL % set ail2 [glob C:/windows/winf*.exe] C:/windows/WINFILE.EXE % foreach name [concat $ail1 $ail2] { set dir [file dirname $name] ; set filename [file tail $name] puts "dir is $dir; puts "name is $filename" } dir is C:/windows name is WINSOCK.DLL dir is C:/windows name is WINFILE.EXE
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 84
exec
exec...... run a new program as a subprocess exec call is similar to invoking a program from the shell prompt exec arg1 ?arg2? ... EXAMPLE 4. % exec /bin/mv a.txt b.txt
Tcl/Tk Training
12/09/2002 86
info
info commands ?pattern? info exists varName info globals ?pattern? info locals ?pattern? info procs ?pattern? info tclversion info script pid EXAMPLE 5. % if {[info exists v]} { incr v $amt} else { set v $amt }
Tcl/Tk Training
12/09/2002 87
Tcl/Tk Training
12/09/2002 88
Exception handling
catch script ?varName? Evaluates and executes script. The return value of catch is the status return of the Tcl interpreter after it executes script If there are no errors in script, this value is TCL_OK. Otherwise it is an error value
Tcl/Tk Training
12/09/2002 89
Exception handling
EXAMPLE 7. % proc errorproc {x} { if {$x > 0} { error "Error generated by error" "Info String for error" $x } } % catch errorproc 1 % puts "after bad proc call: ErrorCode: $errorCode" after bad proc call: ErrorCode: NONE % puts "ERRORINFO:\n$errorInfo\n" ERRORINFO: no value given for parameter "x" to "errorproc" while executing "errorproc"
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 90
Exception handling
EXAMPLE 8. % set errorInfo ""; % catch {errorproc 0} 0 % puts "after proc call with no error: ErrorCode: $errorCode" after proc call with no error: ErrorCode: NONE % puts "ERRORINFO:\n$errorInfo\n" ERRORINFO:
Tcl/Tk Training
12/09/2002 91
EXAMPLE 9. % foreach index [array names env] { puts "$index: $env($index)" } HOME: c:\ COMSPEC: C:\WINDOWS\COMMAND.COM CMDLINE: WIN TMP: C:\WINDOWS\TEMP
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 92
Tcl/Tk Training
12/09/2002 93
Contents . . . . .
Tk
* Relation Between Tcl & Tk * Labels, Text Boxes, Buttons * Check Boxes, Radio Buttons * List Boxes * Scroll Bars * Menus * Geometry Manager(Packer) * Events Handling
Tcl/Tk Training
12/09/2002
Tcl/Tk Training
12/09/2002 95
Labels
Tcl/Tk Training
12/09/2002 96
Labels (Contd..)
set w .abc toplevel $w wm title $w "Label Demonstration frame $w.left frame $w.right pack $w.left $w.right -side left -padx 10 -pady 10 -fill both label $w.left.l1 -text "First label" label $w.left.l2 -text "Second label, raised" -relief raised label $w.left.l3 -text "Third label, sunken" -relief sunken pack $w.left.l1 $w.left.l2 $w.left.l3 -side top -expand yes -pady 2 label $w.right.bitmap -borderwidth 2 -relief sunken \ -bitmap @[file join $tk_library demos images face.bmp] label $w.right.caption -text "Tcl/Tk Proprietor" pack $w.right.bitmap $w.right.caption -side top
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 97
Buttons
Tcl/Tk Training
12/09/2002 98
Buttons (Contd..)
button $w.b1 -text "Peach Puff" -width 10 \ -command "$w config -bg PeachPuff1" button $w.b2 -text "Light Blue" -width 10 \ -command "$w config -bg LightBlue1" button $w.b3 -text "Sea Green" -width 10 \ -command "$w config -bg SeaGreen2" button $w.b4 -text "Yellow" -width 10 \ -command "$w config -bg Yellow1" pack $w.b1 $w.b2 $w.b3 $w.b4 -side top -expand yes -pady 2
Tcl/Tk Training
12/09/2002 99
Check Boxes
Tcl/Tk Training
12/09/2002
Tcl/Tk Training
12/09/2002
Radio Buttons
Tcl/Tk Training
12/09/2002
Tcl/Tk Training
12/09/2002
Message Boxes
Tcl/Tk Training
12/09/2002
Message Box(Contd..)
% message .msg -text "sgsgf gfgsdfgdsg gdfgdG" .msg % pack .msg
Tcl/Tk Training
12/09/2002
List Box
Tcl/Tk Training
12/09/2002
List Box(Contd..)
scrollbar $w.frame.scroll -command "$w.frame.list yview" listbox $w.frame.list -yscroll "$w.frame.scroll set" -setgrid 1 -height 12 pack $w.frame.scroll -side right -fill y pack $w.frame.list -side left -expand 1 -fill both $w.frame.list insert 0 Alabama Alaska Arizona California \ Colorado Connecticut Delaware Florida Georgia Hawaii \ Indiana Iowa Kansas Kentucky Louisiana Maine Maryland \ Massachusetts Michigan Minnesota Mississippi Missouri \ Tennessee Texas Utah Vermont Virginia Washington \ "West Virginia" Wisconsin Wyoming
Tcl/Tk Training
12/09/2002
Text Boxes
text $w.text -relief sunken -bd 2 -yscrollcommand "$w.scroll set" -height 30 scrollbar $w.scroll -command "$w.text yview pack $w.scroll -side right -fill y pack $w.text -expand yes -fill both
Tcl/Tk Training
12/09/2002
Menus
Tcl/Tk Training
12/09/2002
Menu (Contd..)
menu $w.menu set m $w.menu.file menu $m $w.menu add cascade -label "File" -menu $m -underline 0 $m add command -label "Open..." -command {error " just a demo"} $m add command -label "New" -command {error " just a demo"} $m add command -label "Save" -command {error " just a demo"} $m add separator
Tcl/Tk Training
12/09/2002