Post on 27-Nov-2015
description
Agenda - Day 1* Introduction & Expectations* Pre Test* Tcl Theory Session - 1
* Lab Session - 1
* Tcl Theory Session - 2
Tcl/Tk Training 20/10/2004 1
* Break - 1
* Lab Session - 2* Lunch Break
* Tcl Theory Session - 3
* Lab Session - 3* Break - 2
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 20/10/2004 2
Welcome
To The World
of
A quick way to develop Interactive/GUI based applications
Tcl/Tk Training 20/10/2004 3
ObjectiveThe objective of the training is to provide the user:
? A basic familiarity with the syntax,features used inlanguage so as to enable them to write scriptsusing the Tcl/Tk.
Tcl/Tk Training 20/10/2004 4
Prerequisite
The prerequisite for the course is familiaritywith any high level programming language
Tcl/Tk Training 20/10/2004 5
History*Tcl and Tk were created and developed by
‘ John Ousterhout’
* Tcl and Tk were developed in 1987 and 1988respectively
* ‘Scott Stanton’ and ‘Ray Johnson’ ported Tcl& Tk to Windows and the Macintosh in 1994
* Tcl/Tk v8.0 in 1998 with on the fly compilersupport
* Latest version available is 8.4.2
Tcl/Tk Training 20/10/2004 6
Overview* Tcl stands for ‘Tool Command Language’
* Used by over half a million developers worldwide
* Simple and programmable syntax
* Can be used as a standalone application or embedded in application
* Tcl is open source so it's completely free.
* Tk is a graphical user interface toolkit to create powerful GUIs
Overview (Contd..)*Tcl and Tk are highly portable, running on all
flavors of Unix, Linux, Solaris, Windows,Macintosh etc.
* Based on a package of C procedures
Tcl/Tk Training 20/10/2004 7
Contents
* Why scripting language* Why Tcl/Tk* Comparision with other programming languages* What is not covered* References
General
Tcl/Tk Training 20/10/2004 8
Contents Contd. . . . .
* Command substitution
Tcl
Tcl/Tk Training 20/10/2004 9
* How to start Tcl
* Expressions
* Lists and it’s functions with ‘foreach’ loop
* Control flow* Procedures
* Predefined variables
* Puts - For text output
* Variables* Comments
* Global & upvar
Contents Contd. . . . .
* Built in commands eval, upvar,uplevel
* File Operations* Use of exec,info
* Errors & Exception Handling
Tcl/Tk Training 20/10/2004 10
* String Manipulations* Regular expressions* Arrays
* Command line arguments
Contents Contd. . . . .
* Relation Between Tcl & Tk* Labels, Text Boxes, Buttons* Check Boxes, Radio Buttons* List Boxes* Scroll Bars* Menus* Geometry Manager(Packer)* Events Handling
Tk
Tcl/Tk Training 20/10/2004 11
Why Scripting Language ?We should use scripting language if:
* The main task of the application is to integrate and coordinate aset of existing components or applications.
* 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
Tcl Comparison ChartFeatures Tcl Perl Java Script Visual Basic
Rapid development ? ? ??Great regular expressions ? ?Easily extensible ?? Embeddable ?Easy GUIs ?? Internet and Web-enabled ? ? ?
?Cross platform ? ? ?Internationalization support ? ? ?
Tcl/Tk Training 20/10/2004 14
What is not covered ?
* TK object oriented paradigm
* C/C++ programming Methods/Interfaces
* TclPro debugger
* Expect - “talk” with interactive programs
*Advance Tk
Tcl/Tk Training 20/10/2004 15
References
* “Tcl and the Tk Toolkit” by John K. Ousterhout
* “Practical Programming in Tcl and Tk” by Brent Welch
Tcl/Tk Training 20/10/2004 16
Books:
* http://www.tcl.tk
* http://www.sun.com/960710/cover/tcl-syntax.html
* News group “news:comp.lang.tcl”
Internet resources:
Tcl - Tool Command Language
Tcl/Tk Training 20/10/2004 17
How To Start Tcl ?? TheTcl can be run by just typing ‘tclsh’ on command
prompt which will invoke Tcl shell.
? Tcl shell works much like the other shells ..
? Tcl shell takes the command from the user and pass themto the Tcl interpreter
? Each command in Tcl is either a Tcl script or a 'C’ program.
? To exit from tclsh use ‘exit’
Tcl/Tk Training 20/10/2004 18
meminteg>tclsh%exit
meminteg>
Text Output
? The command to output a string in Tcl is the 'puts' command
Tcl/Tk Training 20/10/2004 19
% puts HelloHello%
EXAMPLE 1.
Text Output (Contd..)
Tcl/Tk Training 20/10/2004 20
% puts Hello worldcan not find channel named "Hello"%% puts "Hello World"Hello World%% puts {Hello World}Hello World
?If the string has more than one word, youmust enclose the string in quotes or braces ({}).
EXAMPLE 2.
Comments? A comment can be put on a line by itself, or after a
command string on the same
? Use # to mark a line as comment
? Use ‘;#’ to comment after the command string
Tcl/Tk Training 20/10/2004 21
% puts "Hello World " ;# This is commentHello World% puts "Hello World;" #This is commentwrong # args: should be "puts ?-nonewline? ?channelId? string"% puts "Hello World";Hello World% #This is comment
EXAMPLE 3.
Variables? Tcl stores data as strings, and only converts to numbers
when necessary
? The assignment operator in Tcl is ‘set’.
? Set varName ?value?
Tcl/Tk Training 20/10/2004 22
% ;# Assign a string to variable X% set X "This is a string"This is a string% puts $XThis is a string
EXAMPLE 4.
? If value is specified, then the contents of the variablevarName are set equal to value.
Variables (Contd..)
% ;# Assign a number to variable Y% set Y 1.241.24%% ;# Display the contents of Y% puts $Y1.24%
Tcl/Tk Training 20/10/2004 23
? If varName consists only of alphanumeric characters, and no parenthese, it is a scalar variable.
? Set returns the value of the variable
EXAMPLE 5
Variables (Contd..)
% set x(pk) CRDCRD% puts $x(pk)CRD% set x(dk) IPDFIPDF% 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
? If varName has the form varName(index), it is a memberof an associative array.
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
Evaluation & Substitutions? The evaluation of a command is done in 2 phases. The
first phase is a single pass of substitutions. The secondphase is the evaluation of the resulting command
?Grouping words within double quotes allows substitutions to occur within the quotations. The substituted group is then evaluated as a singleargument
Tcl/Tk Training 20/10/2004 26
% 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
EXAMPLE 8.
Evaluation & Substitutions(Contd..)
Tcl/Tk Training 20/10/2004 27
? The backslash (\) disables substitution for the single character immediately following the backslash.
% ;# Show how a \ affects the $% 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: $Z%
EXAMPLE 9.
Evaluation & Substitutions(Contd..)
% ;# 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 billTcl/Tk Training 20/10/2004 28
? Exceptions backslash rule are \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.
Evaluation & Substitutions(Contd..)
Tcl/Tk Training 20/10/2004 29
? But if backslash comes at the end of a line of text then itcauses the interpreter to ignore the newline, and treat thetext as a single line of text
% puts "This string comes out\on a single line"This string comes out on a single line
EXAMPLE 11.
EXAMPLE 12% set a 100.00100.00% puts "Washington is not on the $a bill" ;# This is not what you wantWashington is not on the 100.00 bill% puts "Lincoln is not on the $$a bill" ;# This is OKLincoln is not on the $100.00 bill% puts "Hamilton is not on the \$a bill" ;# This is not what you wantHamilton is not on the $a bill% puts "Ben Franklin is on the \$$a bill" ;# But, this is OKBen Franklin is on the $100.00 bill% puts "Tab\tTab\tTab"Tab Tab Tab
Tcl/Tk Training 20/10/2004 30
Evaluation & Substitutions(Contd..)? In substitution phase of command evaluation, the two
grouping operators, the brace ({) and the double quote ("),are treated differently by the Tcl
Tcl/Tk Training 20/10/2004 31
% set Z "Albany"Albany% set Z_LABEL "The Capitol of New York is: "The Capitol of New York is:%% puts "\n................. examples of differences between \" and \{"
................. examples of differences between " and {% puts "$Z_LABEL $Z"The Capitol of New York is: Albany
EXAMPLE 13.
Evaluation & Substitutions(Contd..)
% set Z "Albany"Albany% set Z_LABEL "The Capitol of New York is: "The Capitol of New York is:%% puts {$Z_LABEL $Z}$Z_LABEL $Z%
Tcl/Tk Training 20/10/2004 32
? The characters within braces are passed to a commandexactly as they are written
EXAMPLE 14.
EXAMPLE 14. (Contd..)
$Z_LABEL $Z% puts "\n....... examples of differences in nesting \{ and \" "
....... examples of differences in nesting { and "% puts "$Z_LABEL {$Z}"The Capitol of New York is: {Albany}% puts {Who said, "What this country needs is a good $0.05 cigar!"?}Who said, "What this country needs is a good $0.05 cigar!"?%
Tcl/Tk Training 20/10/2004 33
EXAMPLE 14. (Contd..)
% puts "\n................. examples of escape strings"
................. examples of escape strings% puts {There are no substitutions done within braces \n \r \x0a \f \v}There are no substitutions done within braces \n \r \x0a \f \v% puts {But, the escaped newline at the end of a\string is still evaluated as a space}But, the escaped newline at the end of a string is still evaluated as a space
Tcl/Tk Training 20/10/2004 34
Evaluation & Substitutions(Contd..)?We can access to the results of a command by placing the
command in square brackets ([])
Tcl/Tk Training 20/10/2004 35
% 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
EXAMPLE 15.
% set b "\[set y {This is a string within braces within quotes}]"[set y {This is a string within braces within quotes}]% puts "Note the \\ escapes the bracket:\n \$b is: $b"Note the \ escapes the bracket:$b is: [set y {This is a string within braces within quotes}]
% puts "\$y is: $y"can't read "y": no such variable
Tcl/Tk Training 20/10/2004 36
? The exceptions to this rule are as follows:1. A square bracket that is escaped with a \ is considered
as a literal square bracket.2. A square bracket within braces is not modified during
the substitution phase.EXAMPLE 16.
Evaluation & Substitutions(Contd..)
Expressions & Operators? expr - Evaluate an expression
expr arg ?arg arg ...? ? Concatenates arg's, evaluates the result as a Tcl expression,
and returns the value.
? Expressions always yield numeric results
Tcl/Tk Training 20/10/2004 37
% set X 100;100% set Y 256;256% set Z [expr "$Y + $X"]356% puts $Z356
EXAMPLE 17.
Expressions & Operators (Contd..)? A Tcl expression consists of a combination of operands,
operators, and parentheses.
? Integer values may be specified indecimaloctal …………...if the first character of the operand is 0hexadecimal …..if the first two characters are 0x
? Valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16.
? If no numeric interpretation is possible, then an operandis left as a string
?Tcl expressions support non-numeric operands andstring comparisons.
Tcl/Tk Training 20/10/2004 38
EXAMPLE 18.% set a 33% set b 66% expr 3.1 + $a6.1% expr 2+"$a.$b"5.6% expr 4 * [llength "6 2"]8
Tcl/Tk Training 20/10/2004 39
Expressions & Operators (Contd..)?Operands may be specified in any of the following ways: [1] As an numeric value [2] As a Tcl variable, using standard $ notation. [3] As a string enclosed in double-quotes.
Tcl/Tk Training 20/10/2004 40
% set a 55% expr 5+510% expr $a + 510% expr $a + "5"10
EXAMPLE 19.
Expressions & Operators (Contd..)?Operands may be specified in any of the following ways: [4] As a string enclosed in braces. [5] As a Tcl command enclosed in brackets. The command will
be executed and its result will be used as the operand. [6] As a mathematical function whose arguments have
any of the above forms for operands, such as sin($x).
Tcl/Tk Training 20/10/2004 41
% expr $a + {5.33}10.33% expr $a + [set b 4.5]9.5% expr $a + int([set b 4.5])9
EXAMPLE 20.
Expressions & Operators (Contd..)OPERATORSGrouped in decreasing order of precedence:
- + ~ !* / %+ -<< >>< > <= >=== !=& ^ |&& ||x?y:z
Tcl/Tk Training 20/10/2004 42
Expressions & Operators (Contd..)
MATH FUNCTIONSabs cosh log sqrtacos double log10 srandasin exp pow tanatan floor rand tanhatan2 fmod roundceil hypot sincos int sinh
Tcl/Tk Training 20/10/2004 43
Expressions & Operators (Contd..)abs(arg) Returns the absolute value of arg. Arg may be either
integer or floating-point, and the result isreturned in the same form.
pow(x, y) Computes the value of x raised to the power y. If x is negative, y must be an integer value.
Tcl/Tk Training 20/10/2004 44
% expr abs(3.4)3.4% expr abs(-3.4)3.4% expr pow(3,2.5)15.5884572681% expr pow(-3,2.5)domain error: argument not in valid range
EXAMPLE 21.
Expressions & Operators (Contd..)ceil(arg) Returns the smallest integer value not less than arg. floor(arg) Returns the largest integral value not greater than arg. int(arg) If arg is an integer value, returns arg, otherwise
converts arg to integer by truncation and returnsthe converted value.
Tcl/Tk Training 20/10/2004 45
% expr ceil(4.5)5.0% expr floor(4.4)4.0% expr int(4.55)4
EXAMPLE 22.
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 OPERATIONSexpr {"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
Eg.switch abc a - b {format 1} abc {format 2} default {format 3}
will return 2,
Tcl/Tk Training 20/10/2004 47
EXAMPLE 24.
Switch (Contd..) EXAMPLE 25.switch -regexp aaab {
^a.*b$ -b {format 1}a* {format 2}default {format 3}
}will return 1, and switch xyz {
a*{format 2}
default{format 3}
}will return 3.
Tcl/Tk Training 20/10/2004 48
If-else? if - Execute scripts conditionally
if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?? The then and else arguments are optional
% 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
EXAMPLE 26.
While? while - Execute script repeatedly as long as a condition is met
? while test body
set x 0while {$x<10} {
puts "x is $x"incr x
}
? A continue statement within body will stop the execution of thecode and the test will be re-evaluated.
? A break within body will break out of the while loop,and execution will continue with the next line of code after body
Tcl/Tk Training 20/10/2004 50
EXAMPLE 27.
For ? for - “For” loop
? for start test next body
for {set x 0} {$x<10} {incr x} {puts "x is $x"
}
? incr - Increment the value of a variable
? incr varName ?increment?
Tcl/Tk Training 20/10/2004 51
EXAMPLE 28.
Procedures ? proc - Create a Tcl procedure
? proc name args body
? The proc command creates a new Tcl procedure named name
? If the command already existed, then it will be replacedby the new command with the same name.
Tcl/Tk Training 20/10/2004 52
% proc sum {arg1 arg2} {set x [expr $arg1+$arg2];return $x}
%% puts " The sum of 2 + 3 is: [sum 2 3]\n\n"The sum of 2 + 3 is: 5
EXAMPLE 29.
Procedures (Contd..) ? Args is a list of arguments which will be passed to name.
?When proc is invoked, local variables with these names willbe created,and the values to be passed to proc will be copiedto 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.
? The return command will return its argument to the calling program.
? If there is no return, then proc will return the valueof the last command to be executed.
Tcl/Tk Training 20/10/2004 53
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 putsThe arguments were: set i 1$i < 10incr 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 placingthe variable name and the default within braces within args
? A proc will accept a variable number of arguments if the last declared argument is the word args
Tcl/Tk Training 20/10/2004 55
proc example {first {second ""} args} {if {$second == ""} {
puts "There is only one argument and it is: $first";return 1;}
}
EXAMPLE 31.
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
Global & upvar? The scope in which a variable will be evaluated can be
changed with the global or upvar command
? The global command will cause a variable in a local scope to be evaluated in the global scope instead.
? Upvar ties the name of a variable in the current scope toa variable in different scope.
The syntax for upvar is:upvar?level? otherVar1 myVar1 ?otherVar2 myVar2 ...?? Upvar causes myVar1 to become a reference to otherVar1
? By default level is 1, the next level up. If level is 0, thenthe reference is to a variable at the global level.
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.
Lists can be created in several ways:
? 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
Tcl/Tk Training 20/10/2004 59
% set x "a b c"a b c% puts "Item 2 of the list {$x} is: [lindex $x 2]\n"Item 2 of the list {a b c} is: c
EXAMPLE 34.
List (Contd..)
% set y [split 7/4/1776 "/"]7 4 1776% llength $y3% 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
? llength returns the number of elements in a list.
EXAMPLE 35.
Foreach? foreach varname list body
? Foreach will execute the body code one time for each listitem in list.
? On each pass, varname will contain the value of the nextlist item.
% foreach j $x {puts "$j "
}
Tcl/Tk Training 20/10/2004 61
Foreach (Contd..)
% set x "a b c"a b c% 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 xb is item number 1 in list xc is item number 2 in list x
Tcl/Tk Training 20/10/2004 62
EXAMPLE 36.
Manipulating List? Concat
? lappend
% 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 elementa 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 37.
EXAMPLE 38.
% set b [linsert $a 3 "1 2 3"] ;# "1 2 3" is a single elementa 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
?linsert
EXAMPLE 39.
% ;# "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
?lreplace
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.
? lrange list first lastreturns a list composed of the first through last entries inthe list. If first is less than or equal to 0, it is treated as thefirst list element.
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-inclusive2%% 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
Tcl/Tk Training 20/10/2004 68
% 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"
EXAMPLE 41.
EXAMPLE 42.
% 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
?string range string first last
? Returns a string composed of the characters fromfirst to last
Strings (Contd..)? There are 6 string subcommands that do pattern and
string matching.string compare string1 string2returns-1 ..... If string1 is less than string20 ........ If string1 is equal to string21 ........ If string1 is greater than string2
Tcl/Tk Training 20/10/2004 70
Strings (Contd..) EXAMPLE 43.
Tcl/Tk Training 20/10/2004 71
% set name "a is an alphabat"a is an alphabat% set comparison [string compare $name "a"]1% if {$comparison >= 0} {
puts "$name starts with a lowercase letter\n"} else {puts "$name starts with an uppercase letter\n"}
a is an alphabat starts with a lowercase letter
String (contd..) EXERSIZE
? 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
EXPLORE
Regular expressions ? regexp ?switches? exp string ?matchVar? ?subMatch1 ... subMatchN?
Searches string for the regular expression exp. If a parametermatchVar is given, then the substring that matches the regularexpression is copied to matchVar.
Tcl/Tk Training 20/10/2004 73
% 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
EXAMPLE 44.
Regular expressions (Contd..)? regsub ?switches? exp string subSpec varName
Searches string for substrings that match the regular expressionexp and replaces them with subSpec. The resulting string iscopied into varName
Tcl/Tk Training 20/10/2004 74
% set sample "Where there is a will, There is a way."Where there is a will, There is a way.% regsub "way" $sample "lawsuit" sample21% puts "New: $sample2"New: Where there is a will, There is a lawsuit.
EXAMPLE 45.
Regular expressions (contd..) ? Regular expressions can be expressed in just a few rules.
? ^ Matches the beginning of a string
? $ Matches the end of a string
? . Matches any single character
? * Matches any count (0-n) of the previous character
? + Matches any count, but at least 1 of the previous character
? [...] Matches any character of a set of characters
? [^...] Matches any character *NOT* a member of the set of characters following the ^.
Tcl/Tk Training 20/10/2004 75
Arrays? Tclsupports associative arrays in which the index value is
a string.Eg. Set info(Age) 37
array exists arrayName Returns 1 if arrayName is anarray variable. Else returns 0
array names arrayName ?patternReturns a list of the indices forthe associative array
array size arrayNameReturns the number of elements in array arrayName
When an associative array name is given as the argument to the global command, all the elements of the associative arraybecome available to that proc
Tcl/Tk Training 20/10/2004 76
Arrays (Contd..)
Tcl/Tk Training 20/10/2004 77
% 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
EXAMPLE 46.
File access? open fileName ?access? ?permission?
Opens a file and returns a token to be used when accessing the file
? 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.
? w.....Open the file for writing. Create the file if it doesn't exist, or set the length to zero if it does exist
? w+..Open the file for reading and writing. Create the file ifit doesn't exist, or set the length to zero if it does exist.
Tcl/Tk Training 20/10/2004 78
File access (Contd..)
Tcl/Tk Training 20/10/2004 79
% set fileid [open "D:/resumes/tcltutor/pktest.txt" r+]file41d4f4% seek $fileid 0 start% puts $fileid "This is a test.\nIt is only a test"% seek $fileid 0 start% set chars [gets $fileid line1];15% set line2 [gets $fileid];It is only a test% puts "There are $chars characters in \"$line1\""There are 15 characters in "This is a test."% puts "The second line in the file is: \"$line2\""The second line in the file is: "It is only a test"
EXAMPLE 47.
File access (Contd..)
? a ....Open the file for writing. The file must already exist.Set the current location to the end of the file.
? a+...Open the file for writing. The file does not exist, createit.Set the current location to the end of the file.
? permission is an integer to use to set the file access permissions. The default is rw-rw-rw- (0666).
? 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
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 81
File some more commands? read fileID Reads all the remaining bytes from fileID
% seek $fileid 0 start% set buffer [read $fileid];This is a test.It is only a test% puts "\nTotal contents of the file are:\n$buffer"Total contents of the file are:This is a test.It is only a test
% set fileid [open "/windows/temp/testfile" w+]file419cf4% seek $fileid 0 start% puts $fileid "This is a test.\nIt is only a test"
EXAMPLE 1.
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 82
File some more commands?flush fileID Flushes any output that has been buffered for fileID
? eof fileID returns 1 if an End Of File condition exists, otherwise returns 0
% seek $fileid 0 start% while {! [eof $fileid]} {puts "[gets $fileid]";}This is a test.It is only a test
EXAMPLE 2.
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 83
File some more commandsGlob It uses a name matching mechanism
similar to ls, to return a list of names that match a pattern.
filedirname ........ Returns directory portion of pathextension........ Returns file name extensionrootname....... Returns file name without extensiontail.................... Returns filename without
Files (Contd..)
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 84
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:/windowsname is WINSOCK.DLLdir is C:/windowsname is WINFILE.EXE
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 85
File some more commandsatime ................ Returns time of last accessexecutable ..... Returns 1 if file is executable by userexists ................ Returns 1 if file existsisdirectory ...... Returns 1 if entry is a directoryisfile ...............… Returns 1 if entry is a regular filemtime ............… Returns time of last data modificationreadable.........… Returns 1 if file is readable by usersize ..................... Returns file size in byteswritable............ Returns 1 if file is writeable by user
% file size c:/windows/winfile.exe155424% file exists c:/windows/winfile.exe1% file exists c:/windows/winfile1.exe0
exec
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 86
EXAMPLE 4.
% exec /bin/mv a.txt b.txt
exec...... run a new program as a subprocessexec call is similar to invoking a program from the shell prompt
exec arg1 ?arg2? ...
info
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 87
EXAMPLE 5.
% if {[info exists v]} { incr v $amt} else { set v $amt }
info commands ?pattern?info exists varNameinfo globals ?pattern?info locals ?pattern?info procs ?pattern?info tclversioninfo scriptpid
source & eval
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 88
source filename
eval will evaluate any list of stringsand attempt to execute them
eval arg1 ??arg2?? ... ??argn??
% set cmd "OK"OK% eval puts $cmdOK
EXAMPLE 6.
Exception handling
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 89
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
Exception handling
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 90
EXAMPLE 7.% proc errorproc {x} {
if {$x > 0} {error "Error generated by error" "Info String for error" $x}
}% catch errorproc1% 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"
Exception handling
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 91
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:
Command line args
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 92
EXAMPLE 9.
% foreach index [array names env] {puts "$index: $env($index)"}
HOME: c:\COMSPEC: C:\WINDOWS\COMMAND.COMCMDLINE: WINTMP: C:\WINDOWS\TEMP
argc Gives no. of arguments passed to the script
argv0 Gives the name of the script
argv Gives name of all the arguments passed to the script
env Is an array contains the environment varibale
Tk - Tool Kit Language
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 93
Contents . . . . .
* Relation Between Tcl & Tk* Labels, Text Boxes, Buttons* Check Boxes, Radio Buttons* List Boxes* Scroll Bars* Menus* Geometry Manager(Packer)* Events Handling
Tk
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 94
Relation between Tcl & Tk
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 95
Tk extends the built in Tcl commands with additional commands for creating user interface.
Tk is based on ‘C’ library package
Tk can be run using ‘wish’ which icludes ‘tclsh’ as well
Tk provides one command for each class of widgets
Widgets are organized hierarchically, main widgets has the name “.”
Labels
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 96
Labels (Contd..)
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 97
set w .abctoplevel $wwm title $w "Label Demonstration”frame $w.leftframe $w.rightpack $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 raisedlabel $w.left.l3 -text "Third label, sunken" -relief sunkenpack $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
Buttons
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 98
Buttons (Contd..)
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 99
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
Check Boxes
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 100
Check Boxes (Contd..)
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 101
checkbutton $w.b1 -text "Wipers OK" -variable wipers -relief flat
checkbutton $w.b2 -text "Brakes OK" -variable brakes -relief flat
checkbutton $w.b3 -text "Driver Sober" -variable sober -relief flat
pack $w.b1 $w.b2 $w.b3 -side top -pady 2
Radio Buttons
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 102
Radio Buttons (Contd..)
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 103
foreach i {10 12 18 24} {radiobutton $w.left.b$i -text "Point Size $i" -variable size \
-relief flat -value $ipack $w.left.b$i -side top -pady 2 -anchor w
}
Message Boxes
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 104
Message Box(Contd..)
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 105
% message .msg -text "sgsgf gfgsdfgdsg gdfgdG".msg% pack .msg
List Box
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 106
List Box(Contd..)
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 107
scrollbar $w.frame.scroll -command "$w.frame.list yview"listbox $w.frame.list -yscroll "$w.frame.scroll set" -setgrid 1 -height 12pack $w.frame.scroll -side right -fill ypack $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
Text Boxes
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 108
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
Menus
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 109
Menu (Contd..)
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 110
menu $w.menuset m $w.menu.filemenu $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