0% found this document useful (0 votes)
111 views

TCL Tool Command Language

The document outlines an agenda for a Tcl/Tk training covering various topics over multiple sessions including introduction, theory sessions, lab sessions, and breaks. It also provides an overview and history of Tcl/Tk as well as the objectives and prerequisites for the training.

Uploaded by

Agnathavasi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
111 views

TCL Tool Command Language

The document outlines an agenda for a Tcl/Tk training covering various topics over multiple sessions including introduction, theory sessions, lab sessions, and breaks. It also provides an overview and history of Tcl/Tk as well as the objectives and prerequisites for the training.

Uploaded by

Agnathavasi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

Agenda - Day 1

* 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
Welcome
To The World
of

A quick way to develop Interactive/GUI based applications


Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 20/10/2004 2
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 3


Prerequisite

The prerequisite for the course is familiarity


with any high level programming language

Tcl/Tk Training 20/10/2004 4


History
*Tcl and Tk were created and developed by
‘ John Ousterhout’
* Tcl and Tk were developed in 1987 and 1988
respectively
* ‘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 compiler
support
* Latest version available is 8.4.2

Tcl/Tk Training 20/10/2004 5


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

Tcl/Tk Training 20/10/2004 6


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
General
* Why scripting language
* Why Tcl/Tk
* Comparision with other programming languages
* What is not covered
* References

Tcl/Tk Training 20/10/2004 8


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 it’s functions with ‘foreach’ loop

Tcl/Tk Training 20/10/2004 9


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


Why Scripting Language ?
We should use scripting language if:
* The main task of the application is to integrate and coordinate a
set 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


Features
Tcl Comparison Chart
Tcl Perl Java Script Visual Basic

Rapid development ? ? ?
?
Great regular expressions ? ?
Easily extensible ?
? Embeddable ?
Easy GUIs ?
? Internet and Web-enabled ? ? ?
?
Cross platform ? ? ?
Tcl/Tk Training 20/10/2004 14
Internationalization support ? ? ?
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
Books:
* “Tcl and the Tk Toolkit” by John K. Ousterhout
* “Practical Programming in Tcl and Tk” by
Brent Welch

Internet resources:
* http://www.tcl.tk
* http://www.sun.com/960710/cover/tcl-syntax.html
* News group “news:comp.lang.tcl”

Tcl/Tk Training 20/10/2004 16


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 them
to the Tcl interpreter
? Each command in Tcl is either a Tcl script or a 'C’
program.
? To exit from tclsh use ‘exit’
meminteg>tclsh
%exit

meminteg>

Tcl/Tk Training 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


Text Output (Contd..)
?If the string has more than one word, you
must enclose the string in quotes or braces ({}).

EXAMPLE 2.

% puts Hello world


can not find channel named "Hello"
%
% puts "Hello World"
Hello World
%
% puts {Hello World}
Hello World
Tcl/Tk Training 20/10/2004 20
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
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
? Tcl stores data as strings, and only converts to numbers
when necessary
? The assignment operator in Tcl is ‘set’.
? Set varName ?value?
EXAMPLE 4.
% ;# Assign a string to variable X
% set X "This is a string"
This is a string
% puts $X
This is a string

? If value is specified, then the contents of the variable


varName are set equal to value.

Tcl/Tk Training 20/10/2004 22


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..)
? If varName has the form varName(index), it is a member
of an associative array.
EXAMPLE 6
% 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 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 second
phase 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 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
Evaluation & Substitutions(Contd..)
? The backslash (\) disables substitution for the single
character immediately following the backslash.

EXAMPLE 9.

% ;# 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
%

Tcl/Tk Training 20/10/2004 27


Evaluation & Substitutions(Contd..)
? 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.
% ;# 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
Evaluation & Substitutions(Contd..)

? But if backslash comes at the end of a line of text then it


causes the interpreter to ignore the newline, and treat the
text as a single line of text

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
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
EXAMPLE 13.
% 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
Tcl/Tk Training 20/10/2004 31
Evaluation & Substitutions(Contd..)
? The characters within braces are passed to a command
exactly as they are written

EXAMPLE 14.

% 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
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 ([])
EXAMPLE 15.

% 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
Evaluation & Substitutions(Contd..)
? 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.
% 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


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
EXAMPLE 17.
% set X 100;
100
% set Y 256;
256
% set Z [expr "$Y + $X"]
356
% puts $Z
356
Tcl/Tk Training 20/10/2004 37
Expressions & Operators (Contd..)
? A Tcl expression consists of a combination of operands,
operators, and parentheses.
? Integer values may be specified in
decimal
octal …………...if the first character of the operand is 0
hexadecimal …..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 operand
is left as a string
?Tcl expressions support non-numeric operands and
string comparisons.

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


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.
EXAMPLE 19.
% set a 5
5
% expr 5+5
10
% expr $a + 5
10
% expr $a + "5"
10
Tcl/Tk Training 20/10/2004 40
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).
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


Expressions & Operators (Contd..)
OPERATORS
Grouped in decreasing order of precedence:

- + ~ !
* / %
+ -
<< >>
< > <= >=
== !=
& ^ |
&& ||
x?y:z

Tcl/Tk Training 20/10/2004 42


Expressions & Operators (Contd..)
MATH FUNCTIONS
abs cosh log sqrt
acos double log10 srand
asin exp pow tan
atan floor rand tanh
atan2 fmod round
ceil hypot sin
cos 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 is
returned 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.
EXAMPLE 21.
% 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
Tcl/Tk Training 20/10/2004 44
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 returns
the converted value.

EXAMPLE 22.

% expr ceil(4.5)
5.0
% expr floor(4.4)
4.0
% expr int(4.55)
4

Tcl/Tk Training 20/10/2004 45


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
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
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
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
}
? A continue statement within body will stop the execution of the
code 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
For
? for - “For” loop
? for start test next body
EXAMPLE 28.

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


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 replaced
by the new command with the same name.
EXAMPLE 29.
% 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
Tcl/Tk Training 20/10/2004 52
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.
? The return command will return its argument to the
calling program.
? If there is no return, then proc will return the value
of 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 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
? A proc will accept a variable number of arguments if the
last declared argument is the word args
EXAMPLE 31.
proc example {first {second ""} args} {
if {$second == ""} {
puts "There is only one argument and it is: $first";
return 1;
}
}
Tcl/Tk Training 20/10/2004 55
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 to
a 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, then
the 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
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.

% foreach j $x {
puts "$j "
}

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.
? lrange list first last
returns a list composed of the first through last entries in
the list. If first is less than or equal to 0, it is treated as the
first 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-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


Strings (Contd..) EXAMPLE 43.

% 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

Tcl/Tk Training 20/10/2004 71


String (contd..) EXERSIZE
EXPLORE
? 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
? regexp ?switches? exp string ?matchVar? ?subMatch1 ...
subMatchN?
Searches string for the regular expression exp. If a parameter
matchVar is given, then the substring that matches the regular
expression is copied to matchVar.
EXAMPLE 44.

% 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
Regular expressions (Contd..)
? regsub ?switches? exp string subSpec varName
Searches string for substrings that match the regular expression
exp and replaces them with subSpec. The resulting string is
copied into varName
EXAMPLE 45.

% set sample "Where there is a will, There is a way."


Where there is a will, There is a way.
% regsub "way" $sample "lawsuit" sample2
1
% puts "New: $sample2"
New: Where there is a will, There is a lawsuit.

Tcl/Tk Training 20/10/2004 74


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 an


array variable. Else returns 0
array names arrayName ?pattern
Returns a list of the indices for
the associative array
array size arrayName
Returns 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 array
become available to that proc
Tcl/Tk Training 20/10/2004 76
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
? 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 if
it doesn't exist, or set the length to zero if it does exist.
Tcl/Tk Training 20/10/2004 78
File access (Contd..)
EXAMPLE 47.
% 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"
Tcl/Tk Training 20/10/2004 79
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, create
it.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


File some more commands
? read fileID Reads all the remaining bytes from fileID
EXAMPLE 1.

% set fileid [open "/windows/temp/testfile" w+]


file419cf4
% seek $fileid 0 start
% puts $fileid "This is a test.\nIt is only a test"
% 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
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002
81
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
EXAMPLE 2.

% seek $fileid 0 start


% while {! [eof $fileid]} {
puts "[gets $fileid]";
}
This is a test.
It is only a test

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


82
File some more commands
Glob It uses a name matching mechanism
similar to ls, to return a list of names that match a
pattern.
file
dirname ........ Returns directory portion of path
extension........ Returns file name extension
rootname....... Returns file name without extension
tail.................... Returns filename without

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


83
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


File some more commands
atime ................ Returns time of last access
executable ..... Returns 1 if file is executable by user
exists ................ Returns 1 if file exists
isdirectory ...... Returns 1 if entry is a directory
isfile ...............… Returns 1 if entry is a regular file
mtime ............… Returns time of last data modification
readable.........… Returns 1 if file is readable by user
size ..................... Returns file size in bytes
writable............ Returns 1 if file is writeable by user
% file size c:/windows/winfile.exe
155424
% file exists c:/windows/winfile.exe
1
% file exists c:/windows/winfile1.exe
0
Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002
85
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

Prepared by: Pramod k Agarwal/CR&D 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 }

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 87


source & eval
source filename

eval will evaluate any list of strings


and attempt to execute them

eval arg1 ??arg2?? ... ??argn??


EXAMPLE 6.
% set cmd "OK"
OK
% eval puts $cmd
OK

Prepared by: Pramod k Agarwal/CR&D 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

Prepared by: Pramod k Agarwal/CR&D 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:

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 91


Command line args
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
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
Tk - Tool Kit Language

Prepared by: Pramod k Agarwal/CR&D 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

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


94
Relation between Tcl & Tk
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 “.”

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 95


Labels

Prepared by: Pramod k Agarwal/CR&D 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

Prepared by: Pramod k Agarwal/CR&D 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

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002 99


Check Boxes

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


100
Check Boxes (Contd..)

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

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


101
Radio Buttons

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


102
Radio Buttons (Contd..)

foreach i {10 12 18 24} {


radiobutton $w.left.b$i -text "Point Size $i" -variable size \
-relief flat -value $i
pack $w.left.b$i -side top -pady 2 -anchor w
}

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


103
Message Boxes

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


104
Message Box(Contd..)

% message .msg -text "sgsgf gfgsdfgdsg gdfgdG"


.msg
% pack .msg

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


105
List Box

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


106
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

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


107
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

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


108
Menus

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


109
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

Prepared by: Pramod k Agarwal/CR&D Tcl/Tk Training 12/09/2002


110

You might also like