SL - Unit 5 VIII
SL - Unit 5 VIII
UNIT-5
TCL Structure, syntax, Variables and Data in TCL, Control Flow. Data Structures,
input/output, procedures. strings, patterns, files, Advance TC- Eval, source, exec and up level
commands, Name spaces, trapping errors, event driven programs, making applications
internet aware, Nuts and Bolts Internet Programming, Security Issues, C Interface. Tk-Visual
Tool Kits. Fundamental Concepts of Tk. Tk by example, Events and Binding. Perl-Tk.
TCL:
TCL stands for "Tool Command Language" and is pronounced "tickle"; is a simple scripting
language for controlling and extending applications.
TCL is a radically simple open-source interpreted programming language that provides
common facilities such as variables, procedures, and control structures as well as many useful
features that are not found in any other major language.
TCL runs on almost all modern operating systems such as Unix, Macintosh, and Windows
(including Windows Mobile). While TCL is flexible enough to be used in almost any
application imaginable, it does excel in a few key areas, including: automated interaction with
external programs, embedding as a library into application programs, language design, and
general scripting.
TCL was created in 1988 by John Ouster out and is distributed under a BSD style license
(which allows you everything GPL does, plus closing your source code).
The current stable version, in February 2008, is 8.5.1 (8.4.18 in the older 8.4 branch). The
first major GUI extension that works with TCI. is TK, a toolkit that aims to rapid GUI
development. That is why TCL is now more commonly called TCL/TK.
The language features far-reaching introspection, and the syntax, while simple2, is very
different from the Fortran/Algol/C++/Java world.
Although TCL is a string based language there are quite a few object-oriented extensions for
it like Snit3. iner Tel4, and XOTc15 to name a few.
TCL is embeddable: its interpreter is implemented as a library of C procedures that can easily
be incorporated into applications, and each application can extend the core TCL features with
additional commands specific to that application.
Tel was originally developed as a reusable command language for experimental computer
aided design (CAD) tools. The interpreter is implemented as a C library that could be linked
into any application. It is very easy to add new functions to the TCL interpreter, so it is an
ideal reusable "macro language that can be integrated into many applications. However, TCL
is a programming language in its own right, which can be roughly described as a cross-breed
between
LISP/Scheme (mainly for its tail-recursion capabilities).
C (control structure keywords, expr syntax) and
Unix shells (but with more powerful structuring).
TCL Structure
The TCL language has a tiny syntax there is only a single command structure, and a set of
rules to determine how to interpret the commands. Other languages have special syntaxes for
control structures (if, while, repeat...) not so in TCL.
All such structures are implemented as commands. There is a runtime library of compiled "C"
routines, and the 'level' of the GUI interface is quite high.
TCL Comments: If the first character of a command is #, it is a comment.
TCL commands: TCL commands are just words separated by spaces. Commands return
strings. and arguments are just further words.
Command argument command
Argument
Spaces are important
expr 5*3 has a single
argument expr 5*3 has three
arguments
TCL commands are separated by a new line, or a semicolon, and arrays are indexed by text
set a(a\ text index) 4
Syntax
Syntax is just the rules how a language is structured. A simple syntax of English could say(Ignoring
punctuation for the moment). A text consists of one or more sentences A sentence consists of one or
more words' Simple as this is. it also describes Tel's syntax very well if you say "script" for "text",
and "command" for "sentence". There's also the difference that a Tel word can again contain a script
or a command.
So {$x < 0} {set x 0} is a command consisting of three words: if, a condition in braces, a command
(also consisting of three words) in braces. Take this for example is a well-formed Tel command: it
calls Take (which must have been defined before) with the three arguments "this", "for", and
"example". It is up to the command how it interprets its arguments,
e.g. puts acos(-1) will write the string "acos(-1)" to the stdout channel, and return the empty string
"", while expr acos(-1) will compute the arc cosine of-1 and return 3.14159265359 (an approximation
of Pi), or string length acos(-1) will invoke the string command, which again dispatches to its length
sub-command, which determines the length of the second argument and returns 8.A Tel script is a
string that is a sequence of commands, separated by newlines or semicolons. A command is a string
that is a list of words, separated by blanks. The first word is the name of the command; the other
words are passed to it as its arguments.
In Tel, "everything is a command" even what in other languages would be called declaration,
Definition, or control structure. A command can interpret its arguments in any way it wants in
particular, it can implement a different language, like expression. A word is a string that is a simple
word, or one that begins with and ends with the matching) (braces), or one that begins with" and ends
with the matching". Braced words are not evaluated by the parser. In quoted words, substitutions can
occur before the command is called: S[A-Za-z0-9_]+ substitutes the value of the given variable. Or,
if the variable name contains characters outside that regular expression, another layer of bracing helps
the parser to get it right
puts "Guten Morgen. ${Schuler}!"
If the code would say SSchuler, this would be parsed as the value of variable SSch, immediately
followed by the constant string üler. (Part of) a word can be an embedded script: a string in [] brackets
whose contents are evaluated as a script (see above) before the current command is called.In short:
Scripts and commands contain words. Words can again contain scripts and commands. (This can lead
to words more than a page long...) Arithmetic and logic expressions are not part of the Tei language
itself, but the language of the expr command (also used in some arguments of the if, for, while
commands) is basically equivalent to C's expressions, with infix operators and functions.
Rules of TCL
The following rules define the syntax and semantics of the Tel language:
(1) Commands A Tel script is a string containing one or more commands. Semi-colons and newlines
are command separators unless quoted as described below. Close brackets are command terminators
during command substitution (see below) unless quoted.
(2) Evaluation A command is evaluated in two steps. First, the Tel interpreter breaks the command
into words and performs substitutions as described below. These substitutions are performed in the
same way for all commands. The first word is used to locate a command procedure to carry out the
command, then all of the words of the command are passed to the command procedure. The command
procedure is free to interpret each of its words in any way it likes, such as an integer, variable name,
list, or Tcl script. Different commands interpret their words differently.
(3) Words of a command are separated by white space (except for newlines, which are command
separators).
(4) Double quotes If the first character of a word is double-quote (") then the word is terminated by
the next double-quote character. If semi-colons, close brackets, or white space characters (including
newlines) appear between the quotes then they are treated as ordinary characters and included in the
word. Command substitution, variable substitution, and backslash substitution are performed on the
characters between the quotes as described below. The double-quotes are not retained as part of the
word.
(5) Braces If the first character of a word is an open brace (() then the word is terminated by the
matching close brace (1). Braces nest within the word: for each additional open brace there must he
an additional close brace (however, if an open brace or close brace within the word is quoted with a
backslash then it is not counted in locating the matching close brace). No substitutions are performed
on the characters between the braces except for backslash-newline substitutions described below, nor
do semi-colons, newlines, close brackets, or white space receive any special
interpretation. The word will consist of exactly the characters between the outer braces, not including
the braces themselves.
(6) Command substitution If a word contains an open bracket (1) then Tel performs command
substitution. To do this it invokes the Tel interpreter recursively to process the characters following
the open bracket as a Tel script. The script may contain any number of commands and must be
terminated by a close bracket (1). The result of the script (ie. the result of its last command) is
substituted into the word in place of the brackets and all of the characters between them. There may
be any number of command substitutions in a single word. Command
(7) Variable substitution If a word contains a dollar-sign (S) then Tel performs variable substitution:
the dollar-sign and the following characters are replaced in the word by the value of a variable.
Variable substitution may take any of the following forms:
$name
Tel: the Tool Command language
Name is the name of a scalar variable; the name is a sequence of one or more characters that are a
letter, digit, underscore, or namespace separators (two or more colons).
$name(index)
Name gives the name of an array variable and index gives the name of an element within that array.
Name must contain only letters, digits, underscores, and namespace separators, and may be an empty
string.
Command substitutions, variable substitutions, and backslash substitutions are performed on the
characters of index.
$(name)
Name is the name of a scalar variable. It may contain any characters whatsoever except for close
braces. There may be any number of variable substitutions in a single word. Variable substitution is
not performed on words enclosed in braces.
(8) Backslash substitution If a backslash (1) appears within a word then backslash substitution occurs.
In all cases but those described below the backslash is dropped and the following character is treated
as an ordinary character and included in the word. This allows characters such as double quotes, close
brackets, and dollar signs to be included in words without triggering special processing. The
following table lists the backslash sequences that are handled specially, along with the value that
replaces each sequence.
\a
Audible alert (bell) (0x7).
\b
Backspace (0x8).
\f.
Form feed (0xc).
\n
Newline (Oxa).
\n
Carriage-return (Oxd).
\t
Tab (0x9).
\v
Vertical tab (Oxb).
\<newline>whitespce
A single space character replaces the backslash, newline, and all spaces and tabs after the newline.
This backslash sequence is unique in that it is replaced in a separate pre-pass before the command is
actually parsed. This means that it will be replaced even when it occurs between braces, and the
resulting space will he treated as a word separator if it isn't in braces or quotes.
Contents
Literal backslash (\), no special effect.
\000
The digits ooo (one, two, or three of them) give an eight-bit octal value for the Unicode. character
that will be inserted. The upper bits of the Unicode character will be 0.
\hh
The hexadecimal digits hh give an eight-bit hexadecimal value for the Unicode character that will be
inserted. Any number of hexadecimal digits may be present: however, all but the last two are ignored
(the result is always a one-byte quantity). The upper bits of the Unicode character will be 0.
\uhhhh
The hexadecimal digits hhhh (one, two, three, or four of them) give a sixteen-bit hexadecimal value
for the Unicode character that will be inserted. Backslash substitution is not performed on words
enclosed in braces, except for backslash newline as described above.
(9) Comments If a hash character (#) appears at a point where Tel is expecting the first character of
the first word of a command, then the hash character and the characters that follow it, up through the
next newline, are treated as a comment and ignored. The comment character only has significance
when it appears at the beginning of a command.
(10) Order of substitution Each character is processed exactly once by the Tel interpreter as part of
creating the words of a command.
For example, if variable substitution occurs then no further substitutions are performed on the value
of the variable; the value is inserted into the word verbatim. If command substitution occurs then the
nested command is processed entirely by the recursive call to the Tel interpreter, no substitutions are
performed before making the recursive call and no additional substitutions are performed on the result
of the nested script. Substitutions take place from left to right, and each substitution is evaluated
completely before attempting to evaluate the next. Thus, a sequence like set y [set x 0][iner x][iner
x] will always set the variable y to the value, 012.
(11) Substitution and word boundaries Substitutions do not affect the word boundaries of a command.
For example, during variable substitution the entire value of the variable becomes part of a single
word, even if the variable's value contains spaces.
We can also use global variables as an alternative to procedure arguments. For example, we can make
a version of our averaging application which assumes that the input list is stored in a global variable
called "currentList"
proc getCurrentAvg {}\
{
global current List currentLength
set currentl.ength [llength $rl.ist]
if [ ! $currentLength) [return 0.0]
set avg 0.0
fore
set avg [expr $avg/double($currentLength)]
return $avg
}
Then, this adjusted version "getCurrentAvg" could be used elsewhere as follows
global currentList currentLength
set current List "1.10 2.0 3.0"
set a [getCurrent Avg)
puts "List: $currentList Len: $currentlLength Avg: $a"
A procedure can use global variables for persistent storage of information, including the possibility
to test whether the procedure has been called previously; this is useful for procedures that might need
to perform a one-time initialization. In these cases, a procedure will use a global variable which is
not set anywhere else. This means, the first time the procedure is called, the global variable will not
yet exist (recall that the "global" statement declares that a variable will be accessed as a global
variable, but it does not define or create the variable itself).
The TCL command "info exists" will evaluate to true if the given variable exists. For example,
suppose we wanted to make a version of our procedure "getAvg" which keeps an internal count of
how many times it has been called. In this version, we use a global variable named "callCount
getAvg" to keep track of the number of times "getAvg" is called. Because this global variable will
actually be used to store information for the specific use of the "getAvg" procedure, we need to
choose a global variable name which will not be used for a similar purpose in some other procedure.
The first time "getAvg" is called, the global variable does not yet exist, and must be set to zero
set callCount(getAvg) 0
}
iner callCount(getAvg).
puts "get Avg has been used $callCount(getAvg) times"
set n [llength SrList]
if (!$n) (return 0.01
set avg 0.0
foreach r $rList
{
set avg [expr Savg + $r]
{
set avg expr Savg/double($n)]
}
return Savg
}
}
Then, this adjusted version "getCurrentAvg" could be used elsewhere as follows
global currentList currentLength
set current List "1.10 2.0 3.0"
set a [getCurrent Avg)
puts "List: ScurrentList Len: ScurrentlLength Avg: Sa"
A procedure's caller provides the names of one or more of its own variables as arguments to
the procedure.
The procedure then uses the "upvar" command to map these variables from the caller onto
variables in the procedure.
For example, here the caller passes its variable name "count" as the first argument to
procedure "getNAvg":
set count 0
set a [getNAvg count "1.0 2.0 3.0.4.0"]
Then, in this version of procedure "getNArg" the "upvar" command is used to map the first argument
value "SnPtr" onto the procedure's variable called "n"... this means that whenever the procedure gets
or changes the value of variable "n" it will actually be using the caller's variable "count".
proc getNAvg | nPtr rList }\ {
upvar $nPtr n
set n length $rList)
if (!$n) (return 0.01
set avg 0.0
foreach r $rList \ {
set avg [expr $avg + $r]
}
set avg [expr $avg/double($n)]
return $avg
}
Control Flow: In Tel language there are several commands that are used to alter the flow of a
program. When a program is run, its commands are executed from the top of the source file to the
bottom. One by one. This flow can be altered by specific commands. Commands can be executed
multiple times. Some commands are conditional. They are executed only if a specific condition is
met.
The if command
The if command has the following general form:
expr1 "then? bodyl elseif expr2 "then? body2 elseif... ?else? "bodyN" if
The if command is used to check if an expression is true. If it is true, a body of command(s) is then
executed. The body is enclosed by curly brackets,
The if command evaluates an expression. The expression must return a boolean value. In Tel,
1. yes, true mean true and 0. no, false mean false.
!/usr/bin/tclsh
if yes {
puts "This message is always shown"
}
In the above example, the body enclosed by {} characters is always executed.
#!/usr/bin/tclsh
if true then{
puts "This message is always shown"
}
The then command is optional. We can use it if we think, it will make the code more clear. We can
use the else command to create a simple branch. If the expression inside the square brackets following
the if command evaluates to false, the command following the else command is automatically
executed.
#!/usr/bin/tclsh
set sex female if {$sex "male"}
{
puts "It is a boy"
}else {
puts "It is a girl"
}
We have a sex variable. It has "female" string. The Boolean expression evaluates to false and we get
"It is a girl" in the console.
$/girlboy.tcl
It is a girl
We can create multiple branches using the elseif command. The elseif command tests for another
condition, if and only if the previous condition was not met. Note that we can use multiple elseif
commands in our tests.
#!/usr/bin/tclsh
#nums.tcl
puts -nonewline "Enter a number: "
flush stdout
set a [gets stdin]
if{$a < 0}
{
puts "the number is negative"
} elseif {$a==0}
{
puts "the numer is zero" } else
{
Switch command
The switch command matches its string argument against each of the pattern arguments in order. As
soon as it finds a pattern that matches the string it evaluates the following body argument by passing
it recursively to the Tel interpreter and returns the result of that evaluation. If the last pattern argument
is default then it matches anything. If no pattern argument matches string and no default is given,
then the switch command returns an empty string.
#!/usr/bin/tclsh
#switch_cmd.tcl
puts-nonewline "Select a top level domain name:"
flush stdout
gets stdin domain
switch $domain
us { puts "United States"}
de { puts Germany }
sk (puts Slovakia
hu { puts Hungary }
default { puts "unknown" }
}
In our script, we prompt for a domain name. There are several options. If the value equals for example
to us the "United States" string is printed to the console. If the value does not match to any given
value, the default body is executed and unknown is printed to the console.
$./switch_cmd.tcl
Select a top level domain name:sk
$lovakia
We have entered sk string to the console and the program responded with Slovakia, While command:
The while command is a control flow command that allows code to be executed repeatedly based on
a given Boolean condition. The while command executes the commands inside the block enclosed
by curly brackets. The commands are executed each time the expression is evaluated to true.
#!/usr/bin/tclsh
#whileloop.tcl
set i 0
set sum 0
while $i<10 }
{
FOR command: When the number of cycles is know before the loop is initiated, we can use the for
command. In this construct we declare a counter variable, which is automatically increased or
decreased in value during each repetition of the loop.
#!/usr/bin/tclsh
for {set i 0} {$i < 10} {incr i}
{
puts $i
}
In this exam,
for (set ($i < 10) {incr )
In this example, we print numbers 0..9 to the console.
for {set 10} {$i < 10} {incr i)
{
puts $i
}
There are three phases. First, we initiate the counter i to zero. This phase is done only once. Next
comes the condition. If the condition is met, the command inside the for block is executed. Then
comes the third phase: the counter is increased. Now we repeat phases 2 and 3 until the condition is
not met and the for loop is left. In our case, when the counter i is equal to 10, the for loop stops
executing.
$./forloop.tcl
0
1
2
3
4
5
7
8
9
Here we see the output of the forloop.tel script.
The foreach command: The foreach command simplifies traversing over collections of data. It has
no explicit counter. It goes through a list element by element and the current value is copied to a
variable defined in the construct.
#!/usr/bin/tclsh
set planets {Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune}
foreach planet $planet
{
puts $planet
}
In this example, we use the foreach command to go through a list of planets.
foreach planet $planets
{
puts $planet
}
The usage of the foreach command is straightforward. The planets is the list that we iterate through.
The planet is the temporary variable that has the current value from the list. The for each command
goes through all the planets and prints them to the console.
$./planets.tcl
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Running the above Tel script gives this output.
#!/usr/bin/tclsh
set actresses Rachel Weiss Scarlett Johansson Jessica Alba
Marion Cotillard Jennifer Connelly}
foreach (first second) $actresses
puts "$first $second"
In this script, we iterate througn pairs of values of a list.
foreach (first second) $actresses
puts "$first $second"
}
We pick two values from the list at each iteration.
$ Jactresses.tel
Rachel Weiss
Scarlett Johansson
Jessica Alb
Marion Cotillard
Jennifer Connelly
This is the output of actresses tel script
#!/usr/bin/tclsh
foreach i {one two three } item {car coins rocks}
puts "$i $item" }
if (Snum%20] {continue]
If the expression num 2 returns 0, the number in question can be divided by 2. The continue command
is executed and the rest of the cycle is skipped. In our case, the last command of the loop is skipped
and the number is not printed to the console. The next iteration is started.
Data Structures
The list is the basic Tcl data structure.
A list is simply an ordered collection of stuff, numbers. words, strings, or other lists.
Even commands in Tcl are just lists in which the first list entry is the name of a proc, and
subsequent members of the list are the arguments to the proc.
Lists can be created in several way by setting a variable to be a list of values set lst (item 11)
(item 2) (item 31) with the split command set Ist [split "item 1.item 2.item 3" "."} with the
list command, set lst [list "item 1" "item 2" "item 3" An individual list member can he
accessed with the index command. The brief description of these commands is.
list ?arg1? ?arg2?... ?argN?
makes a list of the arguments
split string "splitChars?
Splits the string into a list of items wherever the splitChars occur in the code. SplitChars defaults to
being whitespace. Note that if there are two or more splitChars then each one will be used individually
to split the string. In other words: split "1234567" "36" would return the following list: (12 45
7).lindex list index Returns the index'th item from the list.
Note: lists start from 0, not 1, so the first item is at index 0, the second item is at index 1. and so
on.llength list. Returns the number of elements in a list. The items in list can be iterated through using
the foreach command.foreach varname list body The foreach command 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
In reality, the above form of foreach is the simple form, but the command is quite powerful. It will
allow you to take more than one variable at a time from the list: foreach [a b] Slistofpairs |... ]. You
can even take a variable at a time from multiple lists! For example: foreach a $listOfA b $listOfB
{...}
Examples
set x "a b c"
puts "Item at index 2 of the list ($x) is: [lindex $x 2]\n"
set y [split 7/4/1776 "/"]
puts "We celebrate on the [lindex $y 11'th day of the [lindex $y Ol'th month\n"
set z [list puts "arg 2 is $y"]
puts "A command resembles: Szin"
set i 0
foreach j $x
{
puts " $j is item number $i in list x"
incr i
}
Adding and deleting members of a list
The commands for adding and deleting list members are
concat ?argl arg2... argn?
Concatenates the args into a single list. It also eliminates leading and trailing spaces in the args and
adds a single separator space between args. The argsto concat may be either individual elements, or
lists. If an arg is already a list, the contents of that list is concatenated with the other args. lappend
list Name 7arg1 arg2 each are as a list element. argn? Appends the args to the list listName treating
linsert list Name index arg1 ?arg2... argn Returns a new list with the new list elements inserted just
before the index th element of listName. Each element argument will hecome a separate element of
the new list. If index is less than or equal to zero, then the new elements are inserted at the beginning
of the list. If index has the value end, or if it is greater than or equal to the number of elements in the
list, then the new elements are appended to the list. Ireplace list Name first last ?arg1 argn Returns a
new list with N elements of listName replaced by the args. If first is less than or equal to 0, lreplace
starts replacing from the first element of the list. If first is greater than the end of the list, or the word
end, then Ireplace behaves like lappend. If there are fewer args than the number of positions between
first and last, then the positions for which there are no args are deleted. lset varName index newValue
The Iset command can be used to set elements of a list directly, instead of using Ireplace. Lists in Tel
are the right data structure to use when you have an arbitrary number of things, and you'd like to
access them according to their order in the list. In C, you would use an array. In Tel, arrays are
associated arrays hash tables, as you'll see in the coming sections. If you want to have a collection of
things, and refer to the Nth thing (give me the 10th element in this group of numbers), or go through
them in order via foreach. Take a look at the example code. and pay special attention to the way that
sets of characters are grouped into single list elements.
Example
set b [list a b {c d e {f{g h}}]
puts "Treated as a list: $b\n"
set b [split "a b {c d e} {f{g h}}"]
puts "Transformed by split: $b\n"
set a [concat a b { cde} {f{gh}}]
puts "Concated: $ain"
lappend a [ij K lm )
Input / Output
Tcl uses objects called channels to read and write data.
The channels can be created using the open or socket command.
There are three standard channels available to Tcl scripts without explicitly creating them.
They are automatically opened by the OS for each new application.
They are stdin, stdout and stderr. The standard input, stdin, is used by the scripts to read data.
The standard output, stdout, is used by scripts to write data.
The standard error, stderr, is used by scripts to write error messages. In the first example, we
will work with the puts command. It has the following synopsis:
puts ?-nonewline? ?channelId? string
The channelId is the channel where we want to write text. The channelld is optional. If not specified,
the default stdout is assumed.
#!/usr/bin/telsh
puts "Message 1"
puts stdout "Message 2"
puts stderr "Message 3"
The puts command writes text to the channel.
puts "Message 1"
puts stdout "Message 2"
puts stderr "Message 3"
If we do not specify the channelld, we write to stdout by default. This line does the same thing as the
previous one. We only have explicitly specified the channelld.
We write to the standard error channel. The error messages go to the terminal by default.
$./printing.tcl
Message 1
Message 2
Message 3.
Example output.
The read command: The read command is used to read data from a channel. The optional argument
specifies the number of characters to read. If omitted, the command reads all of the data from the
channel up to the end.
#!/usr/bin/tclsh
set c [read stdin 1
while ($c != "q")
{
puts -nonewline "$c"
set e [read stdin 1]
}
The script reads a character from the standard input channel and then writes it to the standard output
until it encounters the q character.
output until it encounters the q character.
set c [read stdin 1]
We read one character from the standard input channel (stdin).
while ($c != "q"} {
We continue reading characters until the q is pressed.
The gets command
The gets command reads the next line from the channel, returns everything in the line up to
(but
not including) the end-of-line character.
#!/usr/bin/tclsh
puts -nonewline "Enter your name: "
flush stdout
set name [gets stdin]
puts "Hello $name"
The script asks for input from the user and then prints a message. The puts command is used to print
messages to the terminal. The no newline option suppresses the new line character. Tcl buffers output
internally, so characters written with puts may not appear immediately on the output file or device.
The flush command forces the output to appear immediately.
puts-no newline "Enter your name: "
flush stdout
set name [gets stdin)
The script prints all files with the tcl extension to the console. The glob command returns a list of
files that match the tcl pattern.
set files [glob "tcl]
foreach file $files
puts $file
We go through the list of files and print each item of the list to the console.
$./globemd.tcl
attributes.tcl
allfiles. tcl
printing. tcl
hello. tcl
read. tcl
files. tcl
globemd. tcl
write2file tcl
cwd. tcl
readfile. tcl
isfile. tcl
addnumbers. tcl
Procedures
A procedure is a code block containing a series of commands.
Procedures are called functions in many programming languages. It is a good programming
practice for procedures to do only one specific task.
Procedures bring modularity to programs.
The proper use of procedures brings the following advantages
The user defined procedures are procedures created with the proc keyword. The proc
keyword is used to create new Tel commands. The term procedures and commands are often
used interchangeably.
We start with a simple example.
#!/usr/bin/tclsh
proc tclver {}
{
set v [info tclversion]
puts "This is Tcl version $v"
}
tclver
In this script, we create a simple tclver procedure. The procedure prints the version of Tel language.
proc tclver {}
The new procedure is created with the proc command. The {} characters reveal that the procedure
takes no arguments.
set v [info tclversion]
puts "This is Tel version $v’’
tclver
This is the body of the tclver procedure. It is executed when we execute the tclver command. The
hody of the command lies between the curly brackets. The procedure is called by specifying its name.
$. /version.tcl
This is Tcl version 8.6
Sample output.
Procedure arguments:
An argument is a value passed to the procedure.
Procedures can take one or more arguments. If procedures work with data, we must pass the
data to the procedures.
In the following example, we have a procedure which takes one argument.
#!/usr/bin/tclsh
proc ftc (f)
{
return [expr $f9/5 + 321
}
if { $x > $y }
{
return $x
}
Else
{
return $y
}
Here we compute which number is greater. We define two variables which are to be compared.
set a 23
set b 32
set val [maximum $a $b]
We calculate the maximum of the two variables. This is the output of the maximum.tel script.
$./maximum.tcl
The max of 23, 32 is 32
Variable number of arguments
A procedure can take and process variable number of arguments. For this we use the special
arguments and parameter.
#!/usr/bin/tclsh
proc sum (args)
{
set s 0
foreach arg $args
}
iner s $arg
return $s
}
puts [sum 1234]
puts [sum 1 2]
puts [sum 4]
We define a sum procedure which adds up all its arguments. The sum procedure has a special
args argument. It has a list of all values passed to the procedure.
proc sum {args}
{
foreach arg $args
{
iner s $arg
}
We go through the list and calculate the sum.
puts sum 1234]
puts [sum 1 2]
puts [sum 4]
We call the sum procedure three times. In the first case, it takes 4 arguments, in the second
case 2, in the last case one. Output of the variable tel script
$./variable.tel
10
3
4
Implicit arguments
The arguments in Tel procedures may have implicit values. An implicit value is used if no
explicit value is provided.
#!/usr/bin/tclsh
proc power {a {b 2}}
if {$b ==2}
{
return [expr $a $a]
}
set value 1
for {set i 0} {Si <$b} {incr i}
{
set value [expr $value" $a]
}
return $value
}
set v1 [power 5]
set v2 [power 5 4]
puts "5^2 is $v1"
puts "5^2 is $v 1"
puts "5^4 is $v2"
Here we create a power procedure. The procedure has one argument with an implicit value. We can
call the procedure with one and two arguments.
proc power {a {b2}} {
set vl [power 5]
set v2 [power 54]
The second argument b, has an implicit value 2. If we provide only one argument, the power
procedure then returns the value of a to the power 2. We call the power procedure with one and two
arguments. The first line computes the value of 5 to the power 2. The second line value of 5 to the
power 4. Output of the example.
$./implicit.tcl
5^2 is 25
5^4 is 625
Returning multiple values
The return command passes one value to the caller. There is often a need to return multiple values.
In such cases, we can return a list.
#!/usr/bin/tclsh
proc tworandoms {}
{
set r1 [expr round(rand()*10)]
set r2 [expr round(rand()*10)]
return [list $r1 $r2]
puts [two randoms]
puts [two randoms]
puts [two randoms]
nested
puts "outside x is $x"
In the above example, we have a test procedure and a nested procedure defined within the test
procedure. We refer to the global x variable from both procedures.
global x
puts "inside test procedure x is $x"
With the global command, we refer to the global x variable, defined outside the test procedure.
proc nested {}
{
global x
puts "inside nested x is $x"
}
It is possible to create nested procedures. These are procedures defined inside other procedures. We
refer to the global x variable with the global command.
test
nested
We call the test procedure and its nested procedure.
$. /scope3.tcl
inside test procedure x is 1
inside nested x is 1
outside x is l
Strings patterns
Files
The file command manipulates file names and attributes. It has plenty of options.
#!/usr/bin/tclsh
puts [file volumes]
[file mkdir new)
The script prints the system's mounted values and creates. new directory. The file volumes command
returns the absolute paths to the volumes mounted on the system.
puts [file volumes)
[file mkdir new]
The file is directory command determines, whether a file name is a directory. Note that on Unix, a
directory is a special case of a file. The puts command can be used to write to files.
#!/usr/bin/tclsh
set fp [open days w]
set days { Monday Tuesday Wednesday Thursday Friday Saturday Sunday }
puts $fp $days
close $ip
In the script, we open a file for writing. We write days of a week to a file. We open a file named days
for writing. The open command returns a channel id. This data is going to be written to the file. We
used the channel id returned by the open command to write to the file.
set fp [open days w]
set days (Monday Tuesday Wednesday Thursday Friday Saturday Sunday)
puts Síp Sdays
close Sfp
We close the opened channel.
$. /write2file.tcl
$ cat days
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
We run the script and check the contents of the days file. In the following script, we are going to read
data from a file.
S cat languages
Python
Tcl
Visual Basic
Perl
Java
C
C#
Ruby
Scheme
We have a simple file called languages in a directory.
#!/usr/bin/tclsh
Ruby
Scheme
Sample run of the readfile.tel script.
The eof command checks for end-of-line of a supplied channel.
#!/usr/bin/tclsh
set fp[open languages]
while {![eof $tp]}
{
puts [gets $fp]
}
close $f
We use the cof command to read the contents of a file.
Eval
One difference between Tcl and most other compilers is that Tcl will allow an executing
program to create new commands and execute them while running.
A tcl command is defined as a list of strings in which the first string is a command or proc.
Any string or list which meets this criteria can be evaluated and executed.
The eval command will evaluate a list of strings as though they were commands typed at the
% prompt or sourced from a file.
The eval command normally returns the final value of the commands being evaluated. If the
commands being evaluated throw an error (for example, if there is a syntax error in one of the
strings), then eval will will throw an error.
Note that either concat or list may be used to create the command string, but that these two
commands will create slightly different command strings.
eval arg1 ??arg2??.... ??argn??
Evaluates arg! argn as one or more Tel commands.
The args are concatenated into a string, and passed to tcl eval to evaluate and execute.
Eval returns the result for error code) of that evaluation.
Example
set cmd {puts "Evaluating a puts"}
puts "CMD IS: $cmd"
eval $cmd
if (string match [info procs new ProcA] ""]}
{
puts "\nDefining newProcA for this invocation"
set num 0:
set end "proc new ProcA"
set emd [concat $cmd "{} {\n"]
set emd [concat $cmd "global num:\n"]
set emd [concat $emd "iner num:\n"]
set cmd [concat $cmd" return \"/tmp/TMP.[pid].\ $num\":\n"]
set cmd [concat $cmd")"]
eval Semd
}
puts "In The body of newProcA is: An info body new ProcA]\n"
puts "new ProcA returns: newProcA]"
puts "new ProcA returns: [newProcA]"
#
# Define a proc using lists
#
all open resource files, which include the current application and any loaded C extensions.
Alternatively, you may specify the fileName where the TEXT resource can be found.
source fileName
source -rsrc resourceName ?fileName?
source-rsrcid resourceld ?fileName?
Tk - Overview
Tk refers to Toolkit and it provides cross platform GUI widgets, which helps you in building
a Graphical User Interface.
It was developed as an extension to Tcl scripting language by John Ousterhout.
Tk remained in development independently from Tcl with version being different to each
other, before, it was made in sync with Tcl in v8.0.
Features of Tk
It is cross platform with support for Linux, Mac OS, Unix, and Microsoft Windows operating systems.
It is an open source.
It provides high level of extendibility.
It is customizable.
It is configurable.
It provides a large number of widgets.
It can be used with other dynamic languages and not just Tcl.
GUI looks identical across platforms.
Applications Built in Tk
Tk - Environment
Generally, all Mac and Linux mac come with Tk pre-installed. In case, it's not available or you
need the latest version, then you may need to install it. Windows don't come with Tcl/Tk and
you may need to use its specific binary to install it.
1. The Tk Interpreter
It is just a small program that enables you to type Tk commands and have them executed line
by line. It stops execution of a tcl file in case, it encounters an error unlike a compiler that
executes fully.
#!/usr/bin/wish
The following section explains only how to install Tcl/Tk on each of the available platforms.
Installation on Windows
Tk - Special Variables
In Tk, we classify some of the variables as special variables and they have a predefined
usage/functionality. The list of special variables is listed below.
1 tk_library
Used for setting the location of standard Tk libraries.
2 tk_patchLevel
Refers to the current patch level of the Tk interpreter.
3 tk_strictMotif
When non-zero, Tk tries to adhere to Motif look-and-feel as closely as possible.
4 tk_version
Displays the Tk version.
Tk - Widgets Overview
Creating a Widget
The type here refers to the widget type like button, label, and so on. Arguments can be optional and
required based on individual syntax of each widget. The options range from size to formatting
of each component.
Widget uses a structure similar to naming packages. In Tk, the root window is named with a
period (.) and an element in window, for example button is named .myButton1. The variable
name should start with a lowercase letter, digit, or punctuation mark (except a period). After
the first character, other characters may be uppercase or lowercase letters, numbers, or
punctuation marks (except periods). It is recommended to use a lowercase letter to start the
label.
The colors can be declared using name like red, green, and so on. It can also use hexadecimal
representing with #. The number of hexadecimal digits can be 3, 6, 9, or 12.
Dimension Convention
The default unit is pixels and it is used when we specify no dimension. The other dimensions
are i for inches, m for millimeters, c for centimeters and p for points.
Common Options
There are so many common options available to all widgets and they are listed below in the
following table −
1 -background color
Used to set background color for widget.
2 -borderwidth width
Used to draw with border in 3D effects.
3 -font fontDescriptor
Used to set font for widget.
4 -foreground color
Used to set foreground color for widget.
5 -height number
Used to set height for widget.
-highlightbackground color
6 Used to set the color rectangle to draw around a widget when the widget does not have input
focus.
7 -highlightcolor color
Used to set the color rectangle to draw around a widget when the widget has input focus.
8 -padx number
Sets the padx for the widget.
9 -pady number
Sets the pady for the widget.
-relief condition
10 Sets the 3D relief for this widget. The condition may be raised, sunken, flat, ridge, solid, or
groove.
11 -text text
-textvariable varName
12 Variable associated with the widget. When the text of widget changes, the variable is set
with text of widget.
13 -width number
Sets the width for widget.
#!/usr/bin/wish
grid [label .myLabel -background red -text "Hello World" -relief ridge -borderwidth 3]
-padx 100 -pady 100
When we run the above program, we will get the following output.
Basic widgets
1 Label
Widget for displaying single line of text.
2 Button
Widget that is clickable and triggers an action.
3 Entry
Widget used to accept a single line of text as input.
4 Message
Widget for displaying multiple lines of text.
5 Text
Widget for displaying and optionally edit multiple lines of text.
6 Toplevel
Window with all borders and decorations provided by the Window manager.
Layout Widgets
1 Frame
Container widget to hold other widgets.
Place
2 Widget to hold other widgets in specific place with coordinates of its origin and an exact
size.
3 Pack
Simple widget to organize widgets in blocks before placing them in the parent widget.
4 Grid
Widget to nest widgets packing in different directions.
Selection Widgets
1 Radiobutton
Widget that has a set of on/off buttons and labels, one of which may be selected.
2 Checkbutton
Widget that has a set of on/off buttons and labels, many of which may be selected..
3 Menu
Widget that acts as holder for menu items.
4 Listbox
Widget that displays a list of cells, one or more of which may be selected.
Mega Widgets
1 Dialog
Widget for displaying dialog boxes.
2 Spinbox
Widget that allows users to choose numbers.
3 Combobox
Widget that combines an entry with a list of choices available to the use.
4 Notebook
Tabbed widget that helps to switch between one of several pages, using an index tab.
5 Progressbar
Widget to provide visual feedback to the progress of a long operation like file upload.
6 Treeview
Widget to display and allow browsing through a hierarchy of items more in form of tree.
7 Scrollbar
Scrolling widgets without a text or canvas widgets.
8 Scale
Scale widget to choose a numeric value through sliders.
Other Widgets
1 Canvas
Drawing widget for displaying graphics and images..
Tk - Basic Widgets
Basic widgets are common widgets available in almost all Tk applications. The list of available basic
widgets is given below −
Label
1
Widget for displaying single line of text.
Button
2
Widget that is clickable and triggers an action.
Entry
3
Widget used to accept a single line of text as input.
Message
4
Widget for displaying multiple lines of text.
Text
5
Widget for displaying and optionally edit multiple lines of text.
Toplevel
6
Widget used to create a frame that is a new top level window.
#!/usr/bin/wish
When we run the above program, we will get the following output −
Tk - Layout Widgets
Layout widgets are used to handle layouts for the Tk application. Frame widget is used group other
widgets and place, pack, and grid are layout manager to give you total control over your adding
to windows. The list of available layout widgets are as shown below −
Frame
1
Container widget to hold other widgets.
Place
2
Widget to hold other widgets in specific place with coordinates of its origin and an exact
size.
Pack
3
Simple widget to organize widgets in blocks before placing them in the parent widget.
Grid
4
Widget to nest widgets packing in different directions.
#!/usr/bin/wish
When we run the above program, we will get the following output −
Tk - Selection Widgets
Selection widgets are used to select different options in a Tk application. The list of available selection
widgets are as shown below.
Radiobutton
1
Widget that has a set of on/off buttons and labels, one of which may be selected.
Checkbutton
2
Widget that has a set of on/off buttons and labels, many of which may be selected.
Menu
3
Widget that acts as holder for menu items.
Listbox
4
Widget that displays a list of cells, one or more of which may be selected.
#!/usr/bin/wish
When we run the above program, we will get the following output −
Tk - Canvas Widgets
Canvas is used for providing drawing areas. The syntax for canvas widget is shown below −
Options
The options available for the canvas widget are listed below in the following table −
1 -background color
Used to set background color for widget.
-closeenough distance
2 Sets the closeness of mouse cursor to a displayable item. The default is 1.0 pixel. This value
may be a fraction and must be positive.
3 -scrollregion boundingBox
The bounding box for the total area of this canvas.
4 -height number
Used to set height for widget.
5 -width number
Sets the width for widget.
6 -xscrollincrement size
The amount to scroll horizontally when scrolling is requested.
7 -yscrollincrement size
The amount to scroll vertically when scrolling is requested.
#!/usr/bin/wish
When we run the above program, we will get the following output −
The list of the available widgets for drawing in canvas is listed below −
Line
1
Draws a line.
Arc
2
Draws an arc.
Rectangle
3
Draws a rectangle.
4 Oval
Draws an oval.
Polygon
5
Draws a polygon.
Text
6
Draws a text.
Bitmap
7
Draws a bitmap.
Image
8
Draws an image.
#!/usr/bin/wish
When we run the above program, we will get the following output −
Tk - Mega Widgets
Mega widgets include many complex widgets which is often required in some large scale Tk
applications. The list of available mega widgets are as shown below −
Dialog
1
Widget for displaying dialog boxes.
Spinbox
2
Widget that allows users to choose numbers.
Combobox
3
Widget that combines an entry with a list of choices available to the use.
Notebook
4
Tabbed widget that helps to switch between one of several pages, using an index tab.
Progressbar
5
Widget to provide visual feedback to the progress of a long operation like file upload.
Treeview
6
Widget to display and allow browsing through a hierarchy of items more in form of tree.
Scrollbar
7
Scrolling widgets without a text or canvas widgets.
Scale
8
Scale widget to choose a numeric value through sliders.
#!/usr/bin/wish
When we run the above program, we will get the following output −
Tk - Fonts
There are a number of widgets that supports displaying text. Most of these provides the option of font
attribute. The syntax for creating a font is shown below −
Options
The options available for the font create are listed below in the following table −
1 -family familyName
The name of font family.
2 -size number
The size of font.
3 -weight level
The weight for font.
#!/usr/bin/wish
When we run the above program, we will get the following output −
To get all the fonts available, we can use the following command −
#!/usr/bin/wish
Tk - Images
The image widget is used to create and manipulate images. The syntax for creating image is as
follows −
In the above syntax type is photo or bitmap and name is the image identifier.
Options
The options available for image create are listed below in the following table −
1 -file fileName
The name of the image file name.
2 -height number
Used to set height for widget.
3 -width number
Sets the width for widget.
4 -data string
Image in base 64 encoded string.
#!/usr/bin/wish
The available function for image are listed below in the following table −
5 mage names
Returns the list of images live in memory.
A simple example for using the above image widget commands is shown below −
#!/usr/bin/wish
The image will be deleted visually and from memory once "image delete imgobj" command executes.
In console, the output will be like the following −
400
400
photo
imgobj ::tk::icons::information ::tk::icons::error ::tk::icons::
warning ::tk::icons::question
Tk - Events
Events in its simplest form is handled with the help of commands. A simple example for event
handling is event handling with button and is shown below −
#!/usr/bin/wish
proc myEvent { } {
puts "Event triggered"
}
pack [button .myButton1 -text "Button 1" -command myEvent]
When we run the above program, we will get the following output −
#!/usr/bin/wish
proc delay {} {
for {set j 0} {$j < 100000} {incr j} {}
}
When we run the program, we will get the following output in animated way −
#!/usr/bin/wish
proc addText {} {
label .myLabel -text "Hello ............... " -width 25
pack .myLabel
}
after 1000 addText
When we run the program, we will get the following output after one second −
You can cancel an event using the after cancel command as shown below −
#!/usr/bin/wish
proc addText {} {
label .myLabel -text "Hello ............... " -width 25
pack .myLabel
}
after 1000 addText
after cancel addText
Event Binding
bind arguments
Keyboard Events Example
#!/usr/bin/wish
When we run the program and press a letter X, we will get the following output −
Key Pressed: X
Mouse Events Example
#!/usr/bin/wish
When we run the program and press the left mouse button, we will get an output similar to the following
−
Button 1 Pressed : 89 90
Linking Events with Button Example
#!/usr/bin/wish
proc myEvent { } {
puts "Event triggered"
}
pack [button .myButton1 -text "Button 1" -command myEvent]
bind . ".myButton1 invoke"
When we run the program and press enter, we will get the following output −
Event triggered
Tk - Windows Manager
Window manager is used to handle the top level window. It helps in controlling the size,
position, and other attributes of the window. In Tk, . is used to refer the main window. The
syntax for window command is shown below −
The list of options available for Tk wm command is shown in the following table −
1 aspect windowName a b c d
Tries to maintain the ratio of width/height to be between a/b and c/d.
3 grid windowName w h dx dy
Sets the grid size.
5 deiconify windowName
Brings the screen to normal if minimized.
6 conify windowName
Minimizes the window.
7 state windowName
Returns the current state of window.
8 withdraw windowName
Unmaps the window and removes its details in memory.
16 attributes subOptions
There are lots of attributes available like alpha, full screen and so on.
#!/usr/bin/wish
When we run the above program, we will get the following output −
As you can see alpha is one of the attributes available. The list of commonly used subcommands are
listed below −
1 -alpha number
Sets the alpha for window.
2 -fullscreen number
Number can be 0 for normal screen or 1 for full screen.
3 -topmost number
Sets or returns whether window is topmost.Value can be 0 or 1.
Creating Window
We can use toplevel command to create window and an example is shown below −
#!/usr/bin/wish
toplevel .t
When we run the above program, we will get the following output −
Destroying Window
We can use destroy command to destroy window and an example is shown below −
#!/usr/bin/wish
destroy .t
Tk - Geometry Manager
The geometry manager is used to manage the geometry of the window and other frames. We
can use it to handle the position and size of the window and frames. The layout widgets are
used for this purpose.
wm geometry . wxh+/-x+/-y
Here, w refers to width and h refers to height. It is followed by a '+' or '-' sign with number next referring
to the x position on screen. Similarly the following '+' or '-' sign with number refers to the y
position on screen
#!/usr/bin/wish
wm geometry . 300x200+100+100
When we run the above program, we will get the following output −
Grid Geometry
grid gridName -column number -row number -columnspan number -rowspan number
The column, row, columnspan, or rowspan helps in providing the grid geometry.
#!/usr/bin/wish
When we run the above program, we will get the following output −