0% found this document useful (0 votes)
10 views85 pages

SL Unit-V

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 85

UNIT - V

5.1 TCL
5.1.1 Tcl - Overview

Tcl is shortened form of Tool Command Language. John Ousterhout of the University of
California, Berkeley, designed it. It is a combination of a scripting language and its own interpreter
that gets embedded to the application, we develop with it.

Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2, and Mac OSX. Tcl
is much similar to other unix shell languages like Bourne Shell (Sh), the C Shell (csh), the Korn
Shell (sh), and Perl.

It aims at providing ability for programs to interact with other programs and also for acting as an
embeddable interpreter. Even though, the original aim was to enable programs to interact, you can
find full-fledged applications written in Tcl/Tk.

5.1.2 Features of Tcl

The features of Tcl are as follows −

 Reduced development time.


 Powerful and simple user interface kit with integration of TK.
 Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix
platform.
 Quite easy to get started for experienced programmers; since, the language is so simple that
they can learn Tcl in a few hours or days.
 You can easily extend existing applications with Tcl. Also, it is possible to include Tcl in C,
C++, or Java to Tcl or vice versa.
 Have a powerful set of networking functions.
 Finally, it's an open source, free, and can be used for commercial applications without any
limit.

5.1.3 Applications

Tcl is a general-purpose language and you can find Tcl everywhere. It includes,

 Scalable websites that are often backed by databases.


 High performance web servers build with TclHttpd.
 Tcl with CGI based websites.
 Desktop GUI applications.
 Embedded applications.

5.1.4 Local Environment Setup

If you are willing to set up your environment for Tcl, you need the following two software
applications available on your computer −

 Text Editor
 Tcl Interpreter.
 Text Editor

This will be used to type your program. Examples of a few text editors include Windows Notepad,
OS Edit command, Brief, Epsilon, EMACS, and vim or vi.

Name and version of a text editor can vary on different operating systems. For example, Notepad
will be used on Windows, and vim or vi can be used on windows as well as Linux or UNIX.

The files you create with your text editor are called source files and contain program source code.
The source files for Tcl programs are named with the extension ".tcl".

Before starting your programming, make sure you have one text editor in place and you have enough
experience to write a computer program, save it in a file, build it, and finally execute it.

 The Tcl Interpreter

It is just a small program that enables you to type Tcl 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.

Syntax: commandName argument1 argument2 ... argumentN

Let's have a helloWorld.tcl file as follows. We will use this as a first program, we run on a platform
you choose.

#!/usr/bin/tclsh

puts"Hello World!"
 First Tcl Program

Let us write a simple Tcl program. All Tcl files will have an extension, i.e., .tcl. So, put the
following source code in a test.tcl file.

#!/usr/bin/tclsh

puts"Hello, World!"

Assuming, Tcl environment is setup correctly; let's run the program after switching to file's directory
and then execute the program using −

We will get the following output −

Let us now see the basic structure of Tcl program, so that it will be easy for you to understand basic
building blocks of the Tcl language. In Tcl, we use new line or semicolon to terminate the previous
line of code. But semicolon is not necessary, if you are using newline for each command.

 Comments

Comments are like helping text in your Tcl program and the interpreter ignores them. Comments can
be written using a hash_(#) sign in the beginning.

#!/usr/bin/tclsh

# my first program in Tcl


puts"Hello World!"

When the above code is executed, it produces the following result −

Multiline or block comment is written using 'if' with condition '0'. An example is shown below.
#!/usr/bin/tclsh

if0{
my first program inTcl program
Its very simple
}
puts"Hello World!"

When the above code is executed, it produces the following result −

Inline comments use ;#. An example is given below.

#!/usr/bin/tclsh

puts"Hello World!";#my first printinTcl program

When the above code is executed, it produces the following result −

 Identifiers

A Tcl identifier is a name used to identify a variable, function, or any other user-defined item. An
identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores, dollars ($) , and digits (0 to 9).

Tcl does not allow punctuation characters such as @, and % within identifiers. Tcl is a case
sensitive_ language. Thus Manpower and manpower are two different identifiers in Tcl. Here are
some of the examples of acceptable identifiers –
 Whitespace in Tcl

A line containing only whitespace, possibly with a comment, is known as a blank line, and a Tcl
interpreter totally ignores it.

Whitespace is the term used in Tcl to describe blanks, tabs, newline characters, and comments.
Whitespace separates one part of a statement from another and enables the interpreter to identify
where one element in a statement, such as puts, ends and the next element begins. Therefore, in the
following statement −

#!/usr/bin/tclsh

puts"Hello World!"

There must be at least one whitespace character (usually a space) between “puts” and "Hello
World!" for the interpreter to be able to distinguish them. On the other hand, in the following
statement −

#!/usr/bin/tclsh

puts[expr3+2];#print sum of the 3and2

When the above code is executed, it produces the following result −

No whitespace characters are necessary between 3 and +, or between + and 2; although, you are free
to include some if you wish for the readability purpose.

5.1.5 Tcl - Commands

Tcl is a Tool command language, commands are the most vital part of the language. Tcl commands
are built in-to the language with each having its own predefined function. These commands form the
reserved words of the language and cannot be used for other variable naming. The advantage with
these Tcl commands is that, you can define your own implementation for any of these commands to
replace the original built-in functionality.

Each of the Tcl commands validates the input and it reduces the work of the interpreter.
Tcl command is actually a list of words, with the first word representing the command to be
executed. The next words represent the arguments. In order to group the words into a single
argument, we enclose multiple words with "" or {}.

The syntax of Tcl command is as follows −

Let's see a simple example of Tcl command −

#!/usr/bin/tclsh

puts"Hello, world!"

When the above code is executed, it produces the following result −

In the above code, ‘puts’ is the Tcl command and "Hello World" is the argument1. As said before,
we have used "" to group two words.

Let's see another example of Tcl command with two arguments −

#!/usr/bin/tclsh

putsstdout"Hello, world!"

When the above code is executed, it produces the following result −

In the above code, ‘puts’ is the Tcl command, ‘stdout’ is argument1, and "Hello World" is
argument2. Here, stdout makes the program to print in the standard output device.

 Command Substitution

In command substitutions, square brackets are used to evaluate the scripts inside the square brackets.
A simple example to add two numbers is shown below −
#!/usr/bin/tclsh

puts[expr1+6+9]

When the above code is executed, it produces following result −

 Variable Substitution

In variable substitutions, $ is used before the variable name and this returns the contents of the
variable. A simple example to set a value to a variable and print it is shown below.

#!/usr/bin/tclsh

set a 3
puts $a

When the above code is executed, it produces the following result −

 Backslash Substitution

These are commonly called escape sequences; with each backslash, followed by a letter having its
own meaning. A simple example for newline substitution is shown below −

#!/usr/bin/tclsh

puts"Hello\nWorld"

When the above code is executed, it produces the following result −


5.1.6 Variables and Data in TCL
In Tcl, there is no concept of variable declaration. Once, a new variable name is encountered, Tcl
will define a new variable.

 Variable Naming

The name of variables can contain any characters and length. You can even have white spaces by
enclosing the variable in curly braces, but it is not preferred.

The set command is used for assigning value to a variable. The syntax for set command is,

set variableName value

A few examples of variables are shown below −

#!/usr/bin/tclsh

set variableA 10
set {variable B} test
puts $variableA
puts ${variable B}

When the above code is executed, it produces the following result −

10
test

As you can see in the above program, the $variableName is used to get the value of the variable.

 Dynamic Typing

Tcl is a dynamically typed language. The value of the variable can be dynamically converted to the
required type when required. For example, a number 5 that is stored as string will be converted to
number when doing an arithmetic operation. It is shown below −

#!/usr/bin/tclsh

set variableA "10"


puts $variableA
set sum [expr $variableA +20];
puts $sum

When the above code is executed, it produces the following result −


10
30

 Mathematical Expressions

As you can see in the above example, expr is used for representing mathematical expression. The
default precision of Tcl is 12 digits. In order to get floating point results, we should add at least a
single decimal digit. A simple example explains the above.

#!/usr/bin/tclsh

set variableA "10"


set result [expr $variableA / 9];
puts $result
set result [expr $variableA / 9.0];
puts $result
set variableA "10.0"
set result [expr $variableA / 9];
puts $result

When the above code is executed, it produces the following result −

1
1.1111111111111112
1.1111111111111112

In the above example, you can see three cases. In the first case, the dividend and the divisor are
whole numbers and we get a whole number as result. In the second case, the divisor alone is a
decimal number and in the third case, the dividend is a decimal number. In both second and third
cases, we get a decimal number as result.

In the above code, you can change the precision by using tcl_precision special variable. It is shown
below −

#!/usr/bin/tclsh

set variableA "10"


set tcl_precision 5
set result [expr $variableA / 9.0];
puts $result

When the above code is executed, it produces the following result −


1.1111

 Datatypes in TCL

The primitive data-type of Tcl is string and often we can find quotes on Tcl as string only language.
These primitive data-types in turn create composite data-types for list and associative array. In Tcl,
data-types can represent not only the simple Tcl objects, but also can represent complex objects such
as handles, graphic objects (mostly widgets), and I/O channels. Let's look into the details about each
of the above.

 Simple Tcl Objects

In Tcl, whether it is an integer number, boolean, floating point number, or a string. When you want
to use a variable, you can directly assign a value to it, there is no step of declaration in Tcl. There
can be internal representations for these different types of objects. It can transform one data-type to
another when required. The syntax for assigning value to variable is as follows −

#!/usr/bin/tclsh

set myVariable 18
puts $myVariable

When the above code is executed, it produces the following result −

18

The above statement will create a variable name myVariable and stores it as a string even though, we
have not used double quotations. Now, if we try to make an arithmetic on the variable, it is
automatically turned to an integer. A simple example is shown below −

#!/usr/bin/tclsh

set myVariable 18
puts [expr $myVariable + 6 + 9]

When the above code is executed, it produces the following result −

33

One important thing to note is that, these variables don't have any default values and must be
assigned value before they are used.
If we try to print using puts, the number is transformed into proper string. Having two
representations, internal and external, help Tcl to create complex data structures easily compared to
other languages. Also, Tcl is more efficient due to its dynamic object nature.

 String Representations

Unlike other languages, in Tcl, you need not include double quotes when it's only a single word. An
example can be −

#!/usr/bin/tclsh

set myVariable hello


puts $myVariable

When the above code is executed, it produces the following result −

hello

When we want to represent multiple strings, we can use either double quotes or curly braces. It is
shown below −

#!/usr/bin/tclsh

set myVariable "hello world"


puts $myVariable
set myVariable {hello world}
puts $myVariable

When the above code is executed, it produces the following result −

hello world
hello world

 List

List is nothing but a group of elements. A group of words either using double quotes or curly braces
can be used to represent a simple list. A simple list is shown below −

#!/usr/bin/tclsh

set myVariable {red green blue}


puts [lindex $myVariable 2]
set myVariable "red green blue"
puts [lindex $myVariable 1]
When the above code is executed, it produces the following result −

blue
green

 Associative Array

Associative arrays have an index (key) that is not necessarily an integer. It is generally a string that
acts like key value pairs. A simple example is shown below −

#!/usr/bin/tclsh

set marks(english) 80
puts $marks(english)
set marks(mathematics) 90
puts $marks(mathematics)

When the above code is executed, it produces the following result −

80
90

 Handles

Tcl handles are commonly used to represent files and graphics objects. These can include handles to
network requests and also other channels like serial port communication, sockets, or I/O devices.
The following is an example where a file handle is created.

set myfile [open "filename" r]

5.1.7 Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. Tcl language is rich in built-in operators and provides the following types of
operators −

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Ternary Operator
 Arithmetic Operators

Following table shows all the arithmetic operators supported by Tcl language. Assume variable ‘A’
holds 10 and variable ‘B’ holds 20, then −

Operator Description Example

+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

% Modulus Operator and remainder of after an integer division B % A will give 0

 Relational Operators

Following table shows all the relational operators supported by Tcl language. Assume
variable A holds 10 and variable B holds 20, then –
Operator Description Example

Checks if the values of two operands are equal or not, if yes


== (A == B) is not true.
then condition becomes true.

Checks if the values of two operands are equal or not, if values


!= (A != B) is true.
are not equal then condition becomes true.

Checks if the value of left operand is greater than the value of


> (A > B) is not true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of


< (A < B) is true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is greater than or equal to


>= (A >= B) is not true.
the value of right operand, if yes then condition becomes true.

Checks if the value of left operand is less than or equal to the


<= (A <= B) is true.
value of right operand, if yes then condition becomes true.

 Logical Operators

Following table shows all the logical operators supported by Tcl language. Assume variable A holds
1 and variable B holds 0, then −

Operator Description Example

Called Logical AND operator. If both the operands are non-


&& (A && B) is false.
zero, then condition becomes true.

Called Logical OR Operator. If any of the two operands is non-


|| (A || B) is true.
zero, then condition becomes true.

Called Logical NOT Operator. Use to reverses the logical state


! of its operand. If a condition is true then Logical NOT operator !(A && B) is true.
will make false.

 Bitwise Operators

Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and ^ are
as follows −
p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; now in binary format they will be as follows −

A = 0011 1100

B = 0000 1101

----------------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

The Bitwise operators supported by Tcl language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then −

Operator Description Example

Binary AND Operator copies a bit to the result if it exists in both (A & B) will give 12, which
&
operands. is 0000 1100

(A | B) will give 61, which


| Binary OR Operator copies a bit if it exists in either operand.
is 0011 1101

Binary XOR Operator copies the bit if it is set in one operand but (A ^ B) will give 49, which
^
not both. is 0011 0001

Binary Left Shift Operator. The left operands value is moved left A << 2 will give 240, which
<<
by the number of bits specified by the right operand. is 1111 0000

Binary Right Shift Operator. The left operands value is moved A >> 2 will give 15, which
>>
right by the number of bits specified by the right operand. is 0000 1111
 Ternary Operator

Operator Description Example

?: Ternary If Condition is true? Then value X : Otherwise value Y

 Operators Precedence in Tcl

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.

For example : x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3 * 2 and then adds into 7. Here, operators with the highest
precedence appear at the top of the table, those with the lowest appear at the bottom. Within an
expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Unary +- Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Ternary ?: Right to left


5.1.8 Control Flow

 Decision making Statements

Decision making structures require that the programmer specifies one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.

Following is the general form of a typical decision making structure found in most of the
programming languages –

Tcl language uses the expr command internally and hence it’s not required for us to use expr
statement explicitly.

Tcl language provides following types of decision making statements −

Sr.No. Statement & Description

if statement
1
An 'if' statement consists of a Boolean expression followed by one or more statements.

if...else statement
2
An 'if' statement can be followed by an optional 'else' statement, which executes when the
Boolean expression is false.

nested if statements
3
You can use one 'if' or 'else if' statement inside another 'if' or 'else if' statement(s).

switch statement
4
A switch statement allows a variable to be tested for equality against a list of values.

nested switch statements


5
You can use one switch statement inside another switch statement(s).

 The ? : Operator

We have covered conditional operator ? : in previously, which can be used to


replace if...else statements. It has the following general form −

Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.

The value of a '? expression' is determined like this: Exp1 is evaluated. If it is true, then Exp2 is
evaluated and becomes the value of the entire '? expression.' If Exp1 is false, then Exp3 is evaluated
and its value becomes the value of the expression. An example is shown below.

#!/usr/bin/tclsh

set a 10;
set b [expr $a == 1 ? 20: 30]
puts "Value of b is $b\n"
set b [expr $a == 10 ? 20: 30]
puts "Value of b is $b\n"

When you compile and execute the above program, it produces the following result −

Value of b is 30
Value of b is 20

 Looping Statements:

There may be a situation, where you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

Tcl language provides the following types of loops to handle looping requirements.

Sr.No. Loop Type & Description

while loop
1
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

for loop
2
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.

nested loops
3
You can use one or more loop inside any another while, for or do..while loop.

 Loop Control Statements

Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Tcl supports the following control statements.

Sr.No. Control Statement & Description

break statement
1
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.

continue statement
2
Causes the loop to skip the remainder of its body and immediately retest its condition prior
to reiterating.

 The Infinite Loop

A loop becomes infinite loop if a condition never becomes false. The while loop is traditionally used
for this purpose. You can make an endless loop by leaving the conditional expression as 1.

while {1} {
puts "This loop will run forever."
}

When the conditional expression is absent, it is assumed to be true. Tcl programmers more
commonly use the while {1} construct to signify an infinite loop.

NOTE − You can terminate an infinite loop by pressing Ctrl + C keys.

5.1.9 Data Structures

The three data structures that are available in TCL. The first one is list, the second one is called
associative array, and the third one which is the newest and latest is called dictionary.
List is one of the basic data-type available in Tcl. It is used for representing an ordered collection of
items. It can include different types of items in the same list. Further, a list can contain another list.

An important thing that needs to be noted is that these lists are represented as strings completely and
processed to form individual items when required. So, avoid large lists and in such cases; use array.

 Creating a List

The general syntax for list is given below −

set listName { item1 item2 item3 .. itemn }


# or
set listName [list item1 item2 item3]
# or
set listName [split "items separated by a character"
split_character]

Some examples are given below −

#!/usr/bin/tclsh

set colorList1 {red green blue}


set colorList2 [list red green blue]
set colorList3 [split "red_green_blue" _]
puts $colorList1
puts $colorList2
puts $colorList3

When the above code is executed, it produces the following result −

red green blue


red green blue
red green blue

 Appending Item to a List

The syntax for appending item to a list is given below −

append listName split_character value


# or
lappend listName value
Some examples are given below −

#!/usr/bin/tclsh

set var orange


append var " " "blue"
lappend var "red"
lappend var "green"
puts $var

When the above code is executed, it produces the following result −

orange blue red green


Length of List

The syntax for length of list is given below −

llength listName

Example for length of list is given below −

#!/usr/bin/tclsh

set var {orange blue red green}


puts [llength $var]

When the above code is executed, it produces the following result −

4
List Item at Index

The syntax for selecting list item at specific index is given below −

lindex listname index

Example for list item at index is given below −

#!/usr/bin/tclsh

set var {orange blue red green}


puts [lindex $var 1]

When the above code is executed, it produces the following result −


blue
Insert Item at Index

The syntax for inserting list items at specific index is given below.

linsert listname index value1 value2..valuen

Example for inserting list item at specific index is given below.

#!/usr/bin/tclsh

set var {orange blue red green}


set var [linsert $var 3 black white]
puts $var

When the above code is executed, it produces the following result −

orange blue red black white green

 Replace Items at Indices

The syntax for replacing list items at specific indices is given below −

lreplace listname firstindex lastindex value1 value2..valuen

Example for replacing list items at specific indices is given below.

#!/usr/bin/tclsh

set var {orange blue red green}


set var [lreplace $var 2 3 black white]
puts $var

When the above code is executed, it produces the following result −

orange blue black white

 Set Item at Index

The syntax for setting list item at specific index is given below −

lset listname index value

Example for setting list item at specific index is given below.


#!/usr/bin/tclsh

set var {orange blue red green}


lset var 0 black
puts $var

When the above code is executed, it produces the following result −

black blue red green

 Transform List to Variables

The syntax for copying values to variables is given below −

lassign listname variable1 variable2.. variablen

Example for transforming list into variables is given below −

#!/usr/bin/tclsh

set var {orange blue red green}


lassign $var colour1 colour2
puts $colour1
puts $colour2

When the above code is executed, it produces the following result −

orange
blue
Sorting a List

The syntax for sorting a list is given below −

lsort listname

An example for sorting a list is given below −

#!/usr/bin/tclsh

set var {orange blue red green}


set var [lsort $var]
puts $var

When the above code is executed, it produces the following result −


blue green orange red

An array is a systematic arrangement of a group of elements using indices. The syntax for the
conventional array is shown below.

set ArrayName(Index) value

An example for creating simple array is shown below.

#!/usr/bin/tclsh

set languages(0) Tcl


set languages(1) "C Language"
puts $languages(0)
puts $languages(1)

When the above code is executed, it produces the following result −

Tcl
C Language

 Size of Array

The syntax for calculating size array is shown below.

[array size variablename]

An example for printing the size is shown below.

#!/usr/bin/tclsh

set languages(0) Tcl


set languages(1) "C Language"
puts [array size languages]

When the above code is executed, it produces the following result −

2
 Array Iteration

Though, array indices can be non-continuous like values specified for index 1 then index 10 and so
on. But, in case they are continuous, we can use array iteration to access elements of the array. A
simple array iteration for printing elements of the array is shown below.

#!/usr/bin/tclsh

set languages(0) Tcl


set languages(1) "C Language"
for { set index 0 } { $index < [array size languages] } {
incr index } {
puts "languages($index) : $languages($index)"
}

When the above code is executed, it produces the following result −

languages(0) : Tcl
languages(1) : C Language

 Associative Arrays

In Tcl, all arrays by nature are associative. Arrays are stored and retrieved without any specific
order. Associative arrays have an index that is not necessarily a number, and can be sparsely
populated. A simple example for associative array with non-number indices is shown below.

#!/usr/bin/tclsh

set personA(Name) "Dave"


set personA(Age) 14
puts $personA(Name)
puts $personA(Age)

When the above code is executed, it produces the following result −

Dave
14

 Indices of Array

The syntax for retrieving indices of array is shown below.


[array names variablename]

An example for printing the size is shown below.

#!/usr/bin/tclsh

set personA(Name) "Dave"


set personA(Age) 14
puts [array names personA]

When the above code is executed, it produces the following result −

Age Name

 Iteration of Associative Array

You can use the indices of array to iterate through the associative array. An example is shown
below.

#!/usr/bin/tclsh

set personA(Name) "Dave"


set personA(Age) 14
foreach index [array names personA] {
puts "personA($index): $personA($index)"
}

When the above code is executed, it produces the following result −

personA(Age): 14
personA(Name): Dave

A dictionary is an arrangement for mapping values to keys. The syntax for the conventional
dictionary is shown below −

dict set dictname key value


# or
dict create dictname key1 value1 key2 value2 .. keyn valuen
Some examples for creating a dictionary are shown below −

#!/usr/bin/tclsh

dict set colours colour1 red


puts $colours
dict set colours colour2 green
puts $colours

set colours [dict create colour1 "black" colour2 "white"]


puts $colours

When the above code is executed, it produces the following result −

colour1 red
colour1 red colour2 green
colour1 black colour2 white

 Size of Dict

The syntax for getting size of dict is shown below −

[dict size dictname]

An example for printing the size is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]


puts [dict size $colours]

When the above code is executed, it produces the following result −

 Dictionary Iteration

A simple dictionary iteration for printing keys and valued of the dictionary is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]


foreach item [dict keys $colours] {
set value [dict get $colours $item]
puts $value
}

When the above code is executed, it produces the following result −

black
white

 Value for Key in Dict

The syntax for retrieving value for key in dict is shown below −

[dict get $dictname $keyname]

An example for retrieving value for key is given below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]


set value [dict get $colours colour1]
puts $value

When the above code is executed, it produces the following result −

black

 All Keys in Dict

The syntax for retrieving all keys in dict is shown below −

[dict keys $dictname]

An example for printing all keys is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]


set keys [dict keys $colours]
puts $keys

When the above code is executed, it produces the following result −

colour1 colour2
 All Values in Dict

The syntax for retrieving all values in dict is shown below −

[dict values $dictname]

An example for printing all values is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]


set values [dict values $colours]
puts $values

When the above code is executed, it produces the following result −

black white

 Key Exists in Dict

The syntax for checking if a key exists in dict is shown below −

[dict exists $dictname $key]

An example for checking if a key exists in dict is shown below −

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]


set result [dict exists $colours colour1]
puts $result

When the above code is executed, it produces the following result −

5.1.10 Input/Output-Files

Tcl supports file handling with the help of the built in commands open, read, puts, gets, and close.

A file represents a sequence of bytes, does not matter if it is a text file or binary file.
 Opening Files

Tcl uses the open command to open files in Tcl. The syntax for opening a file is as follows −

open fileName accessMode

Here, filename is string literal, which you will use to name your file and accessMode can have one
of the following values −

Sr.No. Mode & Description

r
1 Opens an existing text file for reading purpose and the file must exist. This is the default
mode used when no accessMode is specified.

w
2 Opens a text file for writing, if it does not exist, then a new file is created else existing file
is truncated.

a
3 Opens a text file for writing in appending mode and file must exist. Here, your program
will start appending content in the existing file content.

4 r+
Opens a text file for reading and writing both. File must exist already.

w+
5 Opens a text file for reading and writing both. It first truncate the file to zero length if it
exists otherwise create the file if it does not exist.

a+
6 Opens a text file for reading and writing both. It creates the file if it does not exist. The
reading will start from the beginning, but writing can only be appended.

 Closing a File

To close a file, use the close command. The syntax for close is as follows −

close fileName

Any file that has been opened by a program must be closed when the program finishes using that
file. In most cases, the files need not be closed explicitly; they are closed automatically when File
objects are terminated automatically.

 Writing a File

Puts command is used to write to an open file.


puts $filename "text to write"

A simple example for writing to a file is shown below.

#!/usr/bin/tclsh

set fp [open "input.txt" w+]


puts $fp "test"
close $fp

When the above code is compiled and executed, it creates a new file input.txt in the directory that it
has been started under (in the program's working directory).

 Reading a File

Following is the simple command to read from a file −

set file_data [read $fp]

A complete example of read and write is shown below −

#!/usr/bin/tclsh

set fp [open "input.txt" w+]


puts $fp "test"
close $fp
set fp [open "input.txt" r]
set file_data [read $fp]
puts $file_data
close $fp

When the above code is compiled and executed, it reads the file created in previous section and
produces the following result −

test

Here is another example for reading file till end of file line by line −

#!/usr/bin/tclsh

set fp [open "input.txt" w+]


puts $fp "test\ntest"
close $fp
set fp [open "input.txt" r]
while { [gets $fp data] >= 0 } {
puts $data
}
close $fp

When the above code is compiled and executed, it reads the file created in previous section and
produces the following result −

test
test

5.1.11 Procedures
Procedures are nothing but code blocks with series of commands that provide a specific reusable
functionality. It is used to avoid same code being repeated in multiple locations. Procedures are
equivalent to the functions used in many programming languages and are made available in Tcl with
the help of proc command.

The syntax of creating a simple procedure is shown below −

proc procedureName {arguments}


{
body
}

A simple example for procedure is given below −

#!/usr/bin/tclsh

proc helloWorld {} {
puts "Hello, World!"
}
helloWorld

When the above code is executed, it produces the following result −

Hello, World!

 Procedures with Multiple Arguments

An example for procedure with arguments is shown below −


#!/usr/bin/tclsh

proc add {a b} {
return [expr $a+$b]
}
puts [add 10 30]

When the above code is executed, it produces the following result −

40

 Procedures with Variable Arguments

An example for procedure with arguments is shown below −

#!/usr/bin/tclsh

proc avg {numbers} {


set sum 0
foreach number $numbers {
set sum [expr $sum + $number]
}
set average [expr $sum/[llength $numbers]]
return $average
}
puts [avg {70 80 50 60}]
puts [avg {70 80 50 }]

When the above code is executed, it produces the following result −

65
66

 Procedures with Default Arguments

Default arguments are used to provide default values that can be used if no value is provided. An
example for procedure with default arguments, which is sometimes referred as implicit arguments is
shown below −

#!/usr/bin/tclsh

proc add {a {b 100} } {


return [expr $a+$b]
}
puts [add 10 30]
puts [add 10]

When the above code is executed, it produces the following result −

40
110

 Recursive Procedures

An example for recursive procedures is shown below −

#!/usr/bin/tclsh

proc factorial {number} {


if {$number <= 1} {
return 1
}
return [expr $number * [factorial [expr $number - 1]]]

}
puts [factorial 3]
puts [factorial 5]

When the above code is executed, it produces the following result −

6
120

5.1.12 Strings

The primitive data-type of Tcl is string and often we can find quotes on Tcl as string only
language. These strings can contain alphanumeric character, just numbers, Boolean, or
even binary data. Tcl uses 16 bit unicode characters and alphanumeric characters can
contain letters including non-Latin characters, number or punctuation.

Boolean value can be represented as 1, yes or true for true and 0, no, or false for false.

 String Representations

Unlike other languages, in Tcl, you need not include double quotes when it's only a single
word. An example can be −
#!/usr/bin/tclsh

set myVariable hello


puts $myVariable

When the above code is executed, it produces the following result −

hello

When we want to represent multiple strings, we can use either double quotes or curly braces. It is
shown below −

#!/usr/bin/tclsh

set myVariable "hello world"


puts $myVariable
set myVariable {hello world}
puts $myVariable

When the above code is executed, it produces the following result −

hello world
hello world

 String Escape Sequence

A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal
character (e.g., '\u02C0').

There are certain characters in Tcl when they are preceded by a backslash they will have special
meaning and they are used to represent like newline (\n) or tab (\t). Here, you have a list of some of
such escape sequence codes −

Escape sequence Meaning

\\ \ character

\' ' character

\" " character

\? ? character
\a Alert or bell

\b Backspace

\f Form feed

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab

Following is the example to show a few escape sequence characters −

#!/usr/bin/tclsh

puts "Hello\tWorld\n\nTutorialspoint";

When the above code is compiled and executed, it produces the following result −

Hello World

 String Command

The list of subcommands for string command is listed in the following table −

Sr.No. Methods & Description

compare string1 string2


1 Compares string1 and string2 lexographically. Returns 0 if equal, -1 if string1
comes before string2, else 1.

first string1 string2


2 Returns the index first occurrence of string1 in string2. If not found, returns -
1.

3 index string index


Returns the character at index.

4 last string1 string2


Returns the index last occurrence of string1 in string2. If not found, returns -1.

5 length string
Returns the length of string.
6 match pattern string
Returns 1 if the string matches the pattern.

7 range string index1 index2


Return the range of characters in string from index1 to index2.

8 tolower string
Returns the lowercase string.

9 toupper string
Returns the uppercase string.

trim string ?trimcharacters?


10 Removes trimcharacters in both ends of string. The default trimcharacters is
whitespace.

trimleft string ?trimcharacters?


11 Removes trimcharacters in left beginning of string. The default trimcharacters
is whitespace.

trimright string ?trimcharacters?


12 Removes trimcharacters in left end of string. The default trimcharacters is
whitespace.

wordend findstring index


13 Return the index in findstring of the character after the word containing the
character at index.

wordstart findstring index


14 Return the index in findstring of the first character in the word containing the
character at index.

Examples of some commonly used Tcl string sub commands are given below.

 String Comparison
#!/usr/bin/tclsh
set s1 "Hello"
set s2 "World"
set s3 "World"
puts [string compare $s1 $s2]
if {[string compare $s2 $s3] == 0} {
puts "String \'s1\' and \'s2\' are same.";
}

if {[string compare $s1 $s2] == -1} {


puts "String \'s1\' comes before \'s2\'.";
}

if {[string compare $s2 $s1] == 1} {


puts "String \'s2\' comes after \'s1\'.";
}
When the above code is compiled and executed, it produces the following result −

-1
String 's1' and 's2' are same.
String 's1' comes before 's2'.
String 's2' comes after 's1'.

 Index of String
#!/usr/bin/tclsh

set s1 "Hello World"


set s2 "o"
puts "First occurrence of $s2 in s1"
puts [string first $s2 $s1]
puts "Character at index 0 in s1"
puts [string index $s1 0]
puts "Last occurrence of $s2 in s1"
puts [string last $s2 $s1]
puts "Word end index in s1"
puts [string wordend $s1 20]
puts "Word start index in s1"
puts [string wordstart $s1 20]

When the above code is compiled and executed, it produces the following result −

First occurrence of o in s1
4
Character at index 0 in s1
H
Last occurrence of o in s1
7
Word end index in s1
11
Word start index in s1
6

 Length of String
#!/usr/bin/tclsh

set s1 "Hello World"


puts "Length of string s1"
puts [string length $s1]
When the above code is compiled and executed, it produces the following result −

Length of string s1
11

 Handling Cases
#!/usr/bin/tclsh

set s1 "Hello World"


puts "Uppercase string of s1"
puts [string toupper $s1]
puts "Lowercase string of s1"
puts [string tolower $s1]

When the above code is compiled and executed, it produces the following result −

Uppercase string of s1
HELLO WORLD
Lowercase string of s1
hello world

 Trimming Characters
#!/usr/bin/tclsh

set s1 "Hello World"


set s2 "World"
puts "Trim right $s2 in $s1"
puts [string trimright $s1 $s2]

set s2 "Hello"
puts "Trim left $s2 in $s1"
puts [string trimleft $s1 $s2]

set s1 " Hello World "


set s2 " "
puts "Trim characters s1 on both sides of s2"
puts [string trim $s1 $s2]

When the above code is compiled and executed, it produces the following result −

Trim right World in Hello World


Hello
Trim left Hello in Hello World
World
Trim characters s1 on both sides of s2
Hello World

 Matching Strings
#!/usr/bin/tclsh

set s1 "[email protected]"
set s2 "*@*.com"
puts "Matching pattern s2 in s1"
puts [string match "*@*.com" $s1 ]
puts "Matching pattern tcl in s1"
puts [string match {tcl} $s1]

When the above code is compiled and executed, it produces the following result −

Matching pattern s2 in s1
1
Matching pattern tcl in s1
0

 Append Command
#!/usr/bin/tclsh

set s1 "Hello"
append s1 " World"
puts $s1

When the above code is compiled and executed, it produces the following result −

Hello World

 Format command

The following table shows the list of format specifiers available in Tcl −

Specifier Use

%s String representation

%d Integer representation

%f Floating point representation


%e Floating point representation with mantissa-exponent form

%x Hexa decimal representation

Some simple examples are given below −

#!/usr/bin/tclsh

puts [format "%f" 43.5]


puts [format "%e" 43.5]
puts [format "%d %s" 4 tuts]
puts [format "%s" "Tcl Language"]
puts [format "%x" 40]

When the above code is compiled and executed, it produces the following result −

43.500000
4.350000e+01
4 tuts
Tcl Language
28

 Scan command

Scan command is used for parsing a string based to the format specifier. Some examples are shown
below.

#!/usr/bin/tclsh

puts [scan "90" {%[0-9]} m]


puts [scan "abc" {%[a-z]} m]
puts [scan "abc" {%[A-Z]} m]
puts [scan "ABC" {%[A-Z]} m]

When the above code is compiled and executed, it produces the following result −

1
1
0
1
5.1.13 Regular Expressions and Patterns
The "regexp" command is used to match a regular expression in Tcl. A regular expression is a
sequence of characters that contains a search pattern. It consists of multiple rules and the following
table explains these rules and corresponding use.

Sr.No. Rule & Description

1 x
Exact match.

2 [a-z]
Any lowercase letter from a-z.

3 .
Any character.

4 ^
Beginning string should match.

5 $
Ending string should match.

6 \^
Backlash sequence to match special character ^.Similarly you can use for other characters.

7 ()
Add the above sequences inside parenthesis to make a regular expression.

8 x*
Should match 0 or more occurrences of the preceding x.

9 x+
Should match 1 or more occurrences of the preceding x.

10 [a-z]?
Should match 0 or 1 occurrence of the preceding x.

11 {digit}
Matches exactly digit occurrences of previous regex expression. Digit that contains 0-9.

12 {digit,}
Matches 3 or more digit occurrences of previous regex expression. Digit that contains 0-9.

{digit1,digit2}
13 Occurrences matches the range between digit1 and digit2 occurrences of previous regex
expression.

Syntax

The syntax for regex is given below −


regexp optionalSwitches patterns searchString fullMatch subMatch1
... subMatchn

Here, regex is the command. We will see about optional switches later. Patterns are the rules as
mentioned earlier. Search string is the actual string on which the regex is performed. Full match is
any variable to hold the result of matched regex result. Submatch1 to SubMatchn are optional
subMatch variable that holds the result of sub match patterns.

Let's look at some simple examples before diving into complex ones. A simple example for a string
with any alphabets. When any other character is encountered the regex, search will be stopped and
returned.

#!/usr/bin/tclsh

regexp {([A-Za-z]*)} "Tcl Tutorial" a b


puts "Full Match: $a"
puts "Sub Match1: $b"

When the above code is executed, it produces the following result −

Full Match: Tcl


Sub Match1: Tcl

 Multiple Patterns

The following example shows how to search for multiple patterns. This is example pattern for any
alphabets followed by any character followed by any alphabets.

#!/usr/bin/tclsh

regexp {([A-Za-z]*).([A-Za-z]*)} "Tcl Tutorial" a b c


puts "Full Match: $a"
puts "Sub Match1: $b"
puts "Sub Match2: $c"

When the above code is executed, it produces the following result −

Full Match: Tcl Tutorial


Sub Match1: Tcl
Sub Match2: Tutorial
A modified version of the above code to show that a sub pattern can contain multiple patterns is
shown below −

#!/usr/bin/tclsh

regexp {([A-Za-z]*.([A-Za-z]*))} "Tcl Tutorial" a b c


puts "Full Match: $a"
puts "Sub Match1: $b"
puts "Sub Match2: $c"

When the above code is executed, it produces the following result −

Full Match: Tcl Tutorial


Sub Match1: Tcl Tutorial
Sub Match2: Tutorial

 Switches for Regex Command

The list of switches available in Tcl are,

 nocase − Used to ignore case.


 indices − Store location of matched sub patterns instead of matched characters.
 line − New line sensitive matching. Ignores the characters after newline.
 start index − Sets the offset of start of search pattern.
 Marks the end of switches

In the above examples, I have deliberately used [A-Z, a-z] for all alphabets, you can easily use -
nocase instead of as shown below −

#!/usr/bin/tclsh

regexp -nocase {([A-Z]*.([A-Z]*))} "Tcl Tutorial" a b c


puts "Full Match: $a"
puts "Sub Match1: $b"
puts "Sub Match2: $c"

When the above code is executed, it produces the following result −

Full Match: Tcl Tutorial


Sub Match1: Tcl Tutorial
Sub Match2: Tutorial
Another example using switches is shown below −

#!/usr/bin/tclsh

regexp -nocase -line -- {([A-Z]*.([A-Z]*))} "Tcl


\nTutorial" a b
puts "Full Match: $a"
puts "Sub Match1: $b"
regexp -nocase -start 4 -line -- {([A-Z]*.([A-Z]*))} "Tcl
\nTutorial" a b
puts "Full Match: $a"
puts "Sub Match1: $b"

When the above code is executed, it produces the following result −

Full Match: Tcl


Sub Match1: Tcl
Full Match: Tutorial
Sub Match1: Tutorial

5.2 Advance TCL


5.2.1 Eval, Source, Exec, Uplevel Commands

In TCL, these commands are used for dynamic evaluation and execution of code:

1. eval: Used to evaluate a Tcl script or command stored in a string. It allows you to construct
and execute code dynamically.

Example:

2. source: Reads and executes a Tcl script file in the current interpreter. It's useful for sourcing
external Tcl scripts into your program.

Example:
3. exec: Executes an external command and returns the result. It's often used for interacting
with the operating system or running other programs.

Example:

4. uplevel: Executes a script in a caller's context. It allows you to run code in a different stack
frame, useful for manipulating variables in calling procedures or accessing variables in
different scopes.

Example:

These commands provide powerful capabilities for dynamic programming and interacting with the
system in Tcl.

5.2.2 Name spaces


Namespace is a container for set of identifiers that is used to group variables and procedures.
Namespaces are available from Tcl version 8.0. Before the introduction of the namespaces, there
was single global scope. Now with namespaces, we have additional partitions of global scope.
 Creating Namespace

Namespaces are created using the namespace command. A simple example for creating namespace
is shown below –

#!/usr/bin/tclsh

namespace eval MyMath {


# Create a variable inside the namespace
variable myResult
}

# Create procedures inside the namespace


proc MyMath::Add {a b } {
set ::MyMath::myResult [expr $a + $b]
}
MyMath::Add 10 23

puts $::MyMath::myResult

When the above code is executed, it produces the following result −

33

In the above program, you can see there is a namespace with a variable myResult and a
procedure Add. This makes it possible to create variables and procedures with the same names under
different namespaces.

 Nested Namespaces

Tcl allows nesting of namespaces. A simple example for nesting namespaces is given below −

#!/usr/bin/tclsh

namespace eval MyMath {


# Create a variable inside the namespace
variable myResult
}

namespace eval extendedMath {


# Create a variable inside the namespace
namespace eval MyMath {
# Create a variable inside the namespace
variable myResult
}
}
set ::MyMath::myResult "test1"
puts $::MyMath::myResult
set ::extendedMath::MyMath::myResult "test2"
puts $::extendedMath::MyMath::myResult

When the above code is executed, it produces the following result −

test1
test2

 Importing and Exporting Namespace

You can see in the previous namespace examples, we use a lot of scope resolution operator and it's
more complex to use. We can avoid this by importing and exporting namespaces. An example is
given below −

#!/usr/bin/tclsh

namespace eval MyMath {


# Create a variable inside the namespace
variable myResult
namespace export Add
}

# Create procedures inside the namespace


proc MyMath::Add {a b } {
return [expr $a + $b]
}

namespace import MyMath::*


puts [Add 10 30]

When the above code is executed, it produces the following result −

40

 Forget Namespace

You can remove an imported namespace by using forget subcommand. A simple example is shown
below –
#!/usr/bin/tclsh

namespace eval MyMath {


# Create a variable inside the namespace
variable myResult
namespace export Add
}

# Create procedures inside the namespace


proc MyMath::Add {a b } {
return [expr $a + $b]
}
namespace import MyMath::*
puts [Add 10 30]
namespace forget MyMath::*

When the above code is executed, it produces the following result −

40

5.2.3 Trapping errors

Error handling in Tcl is provided with the help of error and catch commands. The syntax for each
of these commands is shown below.

 Error syntax
error message info code

In the above error command syntax, message is the error message, info is set in the global variable
errorInfo and code is set in the global variable errorCode.

 Catch Syntax
catch script resultVarName

In the above catch command syntax, script is the code to be executed, resultVarName is variable that
holds the error or the result. The catch command returns 0 if there is no error, and 1 if there is an
error.

An example for simple error handling is shown below −

#!/usr/bin/tclsh

proc Div {a b} {
if {$b == 0} {
error "Error generated by error" "Info String for
error" 401
} else {
return [expr $a/$b]
}
}

if {[catch {puts "Result = [Div 10 0]"} errmsg]} {


puts "ErrorMsg: $errmsg"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
}

if {[catch {puts "Result = [Div 10 2]"} errmsg]} {


puts "ErrorMsg: $errmsg"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
}

When the above code is executed, it produces the following result −

ErrorMsg: Error generated by error


ErrorCode: 401
ErrorInfo:
Info String for error
(procedure "Div" line 1)
invoked from within
"Div 10 0"

Result = 5

As you can see in the above example, we can create our own custom error messages. Similarly, it is
possible to catch the error generated by Tcl. An example is shown below −

#!/usr/bin/tclsh

catch {set file [open myNonexistingfile.txt]} result


puts "ErrorMsg: $result"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"

When the above code is executed, it produces the following result −


ErrorMsg: couldn't open "myNonexistingfile.txt": no such file or
directory
ErrorCode: POSIX ENOENT {no such file or directory}
ErrorInfo:
couldn't open "myNonexistingfile.txt": no such file or directory
while executing
"open myNonexistingfile.txt"

5.2.4 Event driven programs


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 −

A simple program to show delay text animation event is shown below −

#!/usr/bin/wish

proc delay {} {
for {set j 0} {$j < 100000} {incr j} {}
}

label .myLabel -text "Hello................" -width 25


pack .myLabel
set str "Hello................"
for {set i [string length $str]} {$i > -2} {set i [expr $i-
1]} {
.myLabel configure -text [string range $str 0 $i]
update
delay
}
When we run the program, we will get the following output in animated way −

 Event after delay

The syntax for event after delay is shown below −

after milliseconds number command

A simple program to show after delay event is shown below −

#!/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

The syntax for event binding is as shown below −

bind arguments
 Keyboard Events Example
#!/usr/bin/wish

bind . {puts "Key Pressed: %K "}

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

bind . {puts "Button %b Pressed : %x %y "}

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

5.2.5 Making applications internet aware


To make applications internet aware in Tcl, you can use various methods depending on the specific
requirements of your application. Here are some common approaches:

1. HTTP Requests: Use the http package to make HTTP requests to remote servers. This
allows your Tcl application to interact with web APIs, fetch data from URLs, or submit data
to web services.

Example:
2. Sockets: Use socket programming to establish connections to remote servers using TCP or
UDP protocols. This allows for low-level communication with servers, enabling custom
protocols or real-time interactions.

Example:

3. Email: Utilize the smtp package to send emails from your Tcl application. This allows your
application to send notifications, reports, or other messages via email.

Example:
4. FTP: Use the ftp package to transfer files to and from FTP servers. This enables your
application to upload or download files from remote locations.

Example:

By incorporating these methods into your Tcl application, you can enable internet connectivity and
enhance its functionality by interacting with remote servers, services, and resources.

5.2.6 Nuts and Bolts Internet Programming

Nuts and Bolts internet programming involves understanding the fundamental components and
concepts of internet communication. In Tcl, you can achieve internet programming by leveraging
various protocols and libraries. Here's a breakdown of the nuts and bolts:

1. TCP/IP Sockets: The foundation of internet communication. Tcl provides built-in support
for socket programming, allowing you to establish connections to remote hosts using TCP or
UDP protocols.
2. HTTP Protocol: Used for fetching resources from web servers and interacting with web
APIs. Tcl's http package enables you to make HTTP requests and handle responses.
3. SMTP Protocol: Used for sending email messages. Tcl's smtp package facilitates sending
emails programmatically, enabling notifications, alerts, and reports from your application.
4. FTP Protocol: Used for transferring files between hosts. Tcl's ftp package allows you to
upload and download files to and from FTP servers.
5. DNS Resolution: The process of translating domain names into IP addresses. Tcl provides
built-in commands like dns to perform DNS lookups and resolve hostnames.
6. Security: Ensuring secure communication over the internet is crucial. Tcl supports SSL/TLS
encryption for secure communication over protocols like HTTPS, SMTPS, and FTPS.
7. Error Handling and Resilience: Handling network errors and ensuring the resilience of
your application is important. Tcl's catch command allows you to trap errors and handle them
gracefully.
8. Concurrency and Asynchronicity: Internet programming often involves handling multiple
connections concurrently. Tcl's event-driven model, along with tools like fileevent, allows
you to manage asynchronous I/O operations effectively.

Understanding these components and how to use them in Tcl will empower you to develop robust
internet-aware applications, interact with remote services, and leverage the full potential of internet
programming.

5.2.7 Security Issues

While Tcl itself is a relatively secure language, there are some security issues to be aware of when
developing Tcl applications, especially when dealing with user input, external data sources, or
network communication. Here are some common security issues in Tcl:

1. Code Injection: Like many scripting languages, Tcl is vulnerable to code injection attacks if
input from untrusted sources is directly executed using commands like eval or exec. Always
validate and sanitize user input to prevent malicious code execution.
2. Cross-Site Scripting (XSS): When generating HTML content dynamically, improper
handling of user input can lead to XSS vulnerabilities. Ensure that user-supplied data is
properly escaped before embedding it in HTML output to prevent XSS attacks.
3. SQL Injection: If Tcl applications interact with databases, improper handling of user input
in SQL queries can lead to SQL injection vulnerabilities. Use parameterized queries or
prepared statements to prevent SQL injection attacks.
4. File System Access: Tcl applications should be careful when dealing with file system
operations, especially when accepting file paths from user input. Validate file paths and
restrict access to sensitive directories to prevent unauthorized access or directory traversal
attacks.
5. Insecure Dependencies: Tcl applications may rely on external libraries or packages, some of
which may have security vulnerabilities. Regularly update dependencies to the latest secure
versions and use trusted sources for obtaining libraries.
6. Insecure Network Communication: When communicating over the network, Tcl
applications should use secure protocols like HTTPS, SMTPS, or FTPS to encrypt sensitive
data and prevent eavesdropping or man-in-the-middle attacks. Ensure that SSL/TLS
configurations are properly configured and up to date.
7. Sensitive Information Exposure: Avoid exposing sensitive information, such as passwords
or API keys, in plain text within Tcl scripts or configuration files. Use secure storage
mechanisms like environment variables or encrypted configuration files.
8. Privilege Escalation: Tcl applications running with elevated privileges (e.g., as root) should
carefully validate and sanitize user input to prevent privilege escalation attacks, where an
attacker exploits vulnerabilities to gain unauthorized access to system resources.

By addressing these security concerns and following best practices for secure coding, Tcl developers
can minimize the risk of security vulnerabilities in their applications and ensure a safer computing
environment for users.

5.2.8 C Interface

In Tcl, you can create a C interface to extend the functionality of the Tcl interpreter or to integrate
existing C code with Tcl scripts. There are several ways to create a C interface in Tcl:

1. Tcl C API: Tcl provides a C API that allows you to interact with the Tcl interpreter from C
code. You can use this API to create Tcl commands, manipulate Tcl objects, and evaluate Tcl
scripts programmatically. This approach is suitable for creating custom Tcl commands in C.
2. Tcl Extension: You can create Tcl extensions, which are shared libraries written in C that
extend the functionality of the Tcl interpreter. Tcl extensions can define new commands,
procedures, or data types that can be used in Tcl scripts. Extensions are typically loaded into
the Tcl interpreter using the load command.
3. SWIG (Simplified Wrapper and Interface Generator): SWIG is a tool that generates
C/C++ wrapper code to expose C/C++ APIs to various scripting languages, including Tcl.
You can use SWIG to automatically generate Tcl bindings for existing C libraries or APIs,
allowing you to call C functions directly from Tcl scripts.
4. Tcl-DP (Tcl Distributed Programming): Tcl-DP is a library that provides distributed
computing capabilities for Tcl scripts. It allows Tcl scripts to communicate with remote Tcl
interpreters or other applications over a network. Tcl-DP can be used to create distributed
applications or to integrate Tcl scripts with other systems.
5. Embedded Tcl Interpreter: You can embed the Tcl interpreter directly into a C/C++
application using the Tcl library. This allows you to execute Tcl scripts from within your
C/C++ application and exchange data between Tcl and C/C++ code. Embedded Tcl
interpreters are commonly used in applications that require scripting capabilities or dynamic
configuration.

These methods provide different levels of integration between C and Tcl code, allowing you to
choose the approach that best suits your requirements. Whether you need to create custom Tcl
commands, extend Tcl with existing C libraries, or embed Tcl into a larger C/C++ application, there
are various options available for creating a C interface in Tcl.

5.3 Tk
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

Large successful applications have been built in Tcl/Tk.

 Dashboard Soft User Interface


 Forms GUI for Relational DB
 Ad Hoc GUI for Relational DB
 Software/Hardware System Design
 Xtask - Task Management
 Musicology with Tcl and Tk
 Calender app
 Tk mail
 Tk Debugger

5.3.1 Tk-Visual Tool Kits

Tk is a powerful, platform-independent GUI toolkit for Tcl, providing tools to build graphical user
interfaces. While Tk itself is highly capable, there are several additional visual toolkits and libraries
that enhance or extend Tk's functionality. Here are some notable Tk-based visual toolkits:

1. BWidget:
 Description: A collection of high-level widgets for Tk that provides a richer set of
GUI components.
 Features: Includes tree views, combo boxes, progress bars, notebooks (tabbed
interfaces), dialogs, and more.
 Usage: BWidget is used to create more sophisticated and visually appealing interfaces
beyond the basic Tk widgets.
 Example:
2. Tile (Ttk):

 Description: Also known as Ttk, Tile is a themed widget set for Tk that allows for a modern
look and feel with native appearance on different platforms.
 Features: Provides themed versions of standard Tk widgets and new widgets like
comboboxes, progress bars, and treeviews.
 Usage: Ttk is used to create visually consistent applications with a more modern appearance.
 Example:
3. Tkinter (Python Interface to Tk):

 Description: Tkinter is the standard Python binding to the Tk toolkit, providing a convenient
way to build GUIs in Python.
 Features: Includes all standard Tk widgets and integrates seamlessly with Python's syntax
and libraries.
 Usage: Tkinter is widely used for building Python-based GUI applications with Tk.
 Example:
1. TkZinc:
 Description: An extension for Tk that provides a widget for structured graphics. It's
particularly useful for applications that require advanced graphical capabilities.
 Features: Supports high-level graphical objects like curves, text, and images, and
allows for interaction and animation.
 Usage: TkZinc is suitable for applications like CAD tools, data visualization, and
interactive graphical editors.
2. BLT:
 Description: A toolkit that extends Tk with additional widgets, such as graphs, charts,
and barcharts, as well as new commands for vector operations, drag-and-drop, and
more.
 Features: Provides powerful graphing and plotting capabilities, making it suitable for
scientific and engineering applications.
 Usage: BLT is used when advanced data visualization and custom graphical elements
are needed.

These toolkits and libraries enhance the capabilities of Tk, allowing you to build more sophisticated
and visually appealing GUI applications in Tcl and other languages that interface with Tk. By
leveraging these additional toolkits, you can create applications that meet more specific and complex
user interface requirements.

5.3.2 Fundamental Concepts of Tk

Tk is a powerful and flexible GUI toolkit for the Tcl scripting language, which is also accessible
from other languages like Python (via Tkinter). Understanding the fundamental concepts of Tk is
essential for building graphical user interfaces. Here are the key concepts:

1. Widgets

Widgets are the building blocks of a Tk GUI. Each widget represents a different type of user
interface element.

 Common Widgets:

 Button: A clickable button.


 Label: A text or image display.
 Entry: A single-line text input field.
 Text: A multi-line text input field.
 Canvas: A drawing area for graphics.
 Frame: A container for grouping other widgets.

2. Widget Hierarchy

Tk uses a hierarchical structure for widgets, where widgets are organized in a tree-like structure.
Each widget has a parent, except the root window, which is the top-level window of the application.

 Example:
3. Geometry Management

Tk provides geometry managers to control the placement and sizing of widgets within their parent
containers.

 Geometry Managers:
 pack: Arranges widgets in blocks before placing them in the parent widget.
 grid: Arranges widgets in a table-like structure of rows and columns.
 place: Places widgets at an absolute position.
 Example (pack):

Example (grid):

4. Events and Bindings

Tk uses an event-driven model where user actions such as clicks and key presses generate events.
You can bind event handlers to widgets to respond to these events.

 Example:
Using ‘bind’ for more specific events:

5. Options and Styles

Widgets can be customized using options that control their appearance and behavior. Tk 8.5 and
later introduced themed widgets (Ttk), which support styling for a modern look and feel.

 Example:

Using Ttk for styling:


6. Menus

Tk provides support for creating menus, including pull-down menus, context menus, and menu bars.

 Example:

7. Dialogs

Tk provides standard dialogs for common tasks such as opening files, saving files, and displaying
messages.

 Example:

8. Canvas Widget

The canvas widget is a powerful and flexible widget for creating custom drawings, including shapes,
text, and images.

 Example:
9. Variables and Tracing

Tk supports the use of Tcl variables in GUI elements, allowing for dynamic updates. You can trace
variable changes and update the UI accordingly.

 Example:

10. The Main Event Loop

Tk applications run in an event loop, which waits for user actions and dispatches events to the
appropriate handlers.

 Example:
5.3.3 Tk by example

Example 1: Hello World

A simple Tk application that displays a "Hello, World!" message.

Example 2: Button Click

An application with a button that displays a message when clicked.


Example 3: Simple Form

A simple form with labels, entry widgets, and a submit button.

package require Tk

# Create the main window

set mw [tk appname "SimpleForm"]

# Create a frame to contain the form

frame .form

pack .form

# Create labels and entry widgets

label .form.lblName -text "Name:"

entry .form.entName

label .form.lblEmail -text "Email:"

entry .form.entEmail
pack .form.lblName .form.entName -side left -padx 5 -pady 5

pack .form.lblEmail .form.entEmail -side left -padx 5 -pady 5

# Create a submit button

button .form.btnSubmit -text "Submit" -command {

set name [.form.entName get]

set email [.form.entEmail get]

tk_messageBox -message "Name: $name\nEmail: $email"

pack .form.btnSubmit -side bottom -padx 5 -pady 5

# Run the Tk event loop

tk::MainLoop

Example 4: Using Grid Geometry Manager

An example that arranges widgets using the grid geometry manager.

package require Tk

# Create the main window

set mw [tk appname "GridExample"]

# Create a label and entry widgets using the grid manager

label .lblName -text "Name:"

grid .lblName -row 0 -column 0 -sticky w

entry .entName

grid .entName -row 0 -column 1 -padx 5 -pady 5

label .lblEmail -text "Email:"


grid .lblEmail -row 1 -column 0 -sticky w

entry .entEmail

grid .entEmail -row 1 -column 1 -padx 5 -pady 5

# Create a submit button

button .btnSubmit -text "Submit" -command {

set name [.entName get]

set email [.entEmail get]

tk_messageBox -message "Name: $name\nEmail: $email"

grid .btnSubmit -row 2 -columnspan 2 -pady 10

# Run the Tk event loop

tk::MainLoop

Example 5: Canvas Drawing

An example demonstrating drawing shapes on a canvas widget.

package require Tk

# Create the main window

set mw [tk appname "CanvasExample"]

# Create a canvas widget

canvas .c -width 400 -height 300

pack .c -expand true -fill both

# Draw shapes on the canvas


.c create rectangle 50 50 150 150 -fill "blue"

.c create oval 200 50 350 150 -fill "red"

.c create line 50 200 350 200 -width 2 -fill "green"

.c create text 200 250 -text "Canvas Drawing" -font {Arial 16}

# Run the Tk event loop

tk::MainLoop

Example 6: Menu

An example that creates a window with a menu bar.

package require Tk

# Create the main window

set mw [tk appname "MenuExample"]

# Create a menu bar

menu .menubar

.mw configure -menu .menubar

# Create a File menu

menu .menubar.file -tearoff 0

.menubar add cascade -label "File" -menu .menubar.file

.menubar.file add command -label "Open" -command {tk_messageBox -


message "Open File"}

.menubar.file add separator

.menubar.file add command -label "Exit" -command {exit}

# Create a Help menu


menu .menubar.help -tearoff 0

.menubar add cascade -label "Help" -menu .menubar.help

.menubar.help add command -label "About" -command {tk_messageBox -


message "About this application"}

# Run the Tk event loop

tk::MainLoop

These examples cover a range of basic functionalities and demonstrate how to use Tk to create
different types of graphical user interfaces in Tcl. Each example builds upon the fundamental
concepts of widgets, geometry management, events, and more, providing a solid foundation for
further exploration and development.

5.3.4 Events and Binding

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 −

A simple program to show delay text animation event is shown below −

#!/usr/bin/wish

proc delay {} {
for {set j 0} {$j < 100000} {incr j} {}
}

label .myLabel -text "Hello................" -width 25


pack .myLabel
set str "Hello................"
for {set i [string length $str]} {$i > -2} {set i [expr $i-
1]} {
.myLabel configure -text [string range $str 0 $i]
update
delay
}

When we run the program, we will get the following output in animated way −

 Event after delay

The syntax for event after delay is shown below −

after milliseconds number command

A simple program to show after delay event is shown below −

#!/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

The syntax for event binding is as shown below −

bind arguments

 Keyboard Events Example


#!/usr/bin/wish

bind . {puts "Key Pressed: %K "}

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

bind . {puts "Button %b Pressed : %x %y "}

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
Example: Binding a Mouse Click Event
Here’s an example of binding a left mouse click event to a button widget:

package require Tk

# Create a button widget


button .btn -text "Click Me"
pack .btn

# Bind left mouse click event to the button


bind .btn <Button-1> {
tk_messageBox -message "Button Clicked!"
}

# Run the Tk event loop


tk::MainLoop

 Common Events

<Button-1>: Left mouse button click.


<Button-2>: Middle mouse button click.
<Button-3>: Right mouse button click.
<KeyPress> or <Key>: Key press event.
<KeyRelease>: Key release event.
<Motion>: Mouse motion event.
<Enter>: Mouse enters widget.
<Leave>: Mouse leaves widget.
<Configure>: Widget is resized or moved.
<FocusIn>: Widget gains keyboard focus.
<FocusOut>: Widget loses keyboard focus.

Example: Key Press Event


Here’s an example of binding a key press event to an entry widget:

package require Tk

# Create an entry widget


entry .ent
pack .ent

# Bind key press event to the entry widget


bind .ent <KeyPress> {
tk_messageBox -message "Key Pressed: %A"
}

# Run the Tk event loop


tk::MainLoop

 Event Detail Substitutions


In the event binding script, you can use percent substitutions to get details about the event. Some
common substitutions include:

%A: The ASCII code of the key pressed.


%K: The keysym (key symbol) of the key pressed.
%x and %y: The x and y coordinates of the mouse pointer relative to the widget.
%X and %Y: The x and y coordinates of the mouse pointer relative to the screen.
%W: The pathname of the window to which the event was delivered.
Example: Mouse Motion Event with Details
Here’s an example that shows the coordinates of the mouse pointer when it moves over a canvas
widget:

package require Tk

# Create a canvas widget


canvas .c -width 400 -height 300
pack .c

# Bind mouse motion event to the canvas widget


bind .c <Motion> {
set x %x
set y %y
.c delete coords
.c create text 10 10 -anchor nw -text "Mouse at ($x, $y)" -tags
coords
}

# Run the Tk event loop


tk::MainLoop

 Advanced Binding with Multiple Events


You can bind multiple events to the same widget or even to the same script. Here’s an example that
binds both left and right mouse button clicks to a label widget:

package require Tk
# Create a label widget
label .lbl -text "Click me with left or right mouse button"
pack .lbl

# Bind left mouse click


bind .lbl <Button-1> {
tk_messageBox -message "Left mouse button clicked!"
}

# Bind right mouse click


bind .lbl <Button-3> {
tk_messageBox -message "Right mouse button clicked!"
}

# Run the Tk event loop


tk::MainLoop

 Binding to Classes of Widgets


You can bind an event to all widgets of a particular class. For example, binding a key press event to
all entry widgets:

package require Tk

# Create entry widgets


entry .ent1
entry .ent2
pack .ent1 .ent2

# Bind key press event to all entry widgets


bind Entry <KeyPress> {
tk_messageBox -message "Key Pressed in Entry: %A"
}

# Run the Tk event loop


tk::MainLoop
By understanding and utilizing events and bindings, you can make your Tk applications interactive
and responsive to user input.

5.3.5 Perl-Tk
Perl/Tk, often referred to as Perl-Tk, is a popular extension of Perl that allows for the creation of
graphical user interfaces (GUIs) using the Tk toolkit. It combines the flexibility of Perl with the
powerful GUI capabilities of Tk. Here are some fundamental concepts and examples to help you get
started with Perl-Tk.
 Installing Perl-Tk

Before using Perl-Tk, you need to install the module. You can install it from CPAN (Comprehensive
Perl Archive Network):

 Basic Perl-Tk Program

Here's a simple "Hello, World!" program in Perl-Tk:

 Widgets

Widgets are the basic building blocks of a Tk GUI. Common widgets include buttons, labels, entry
fields, text areas, and more. Here are examples of different widgets:

 Label
 Button

A button that prints a message when clicked:

 Entry

An entry widget for text input:


 Geometry Management

Geometry management in Perl-Tk controls the placement and sizing of widgets. The two primary
geometry managers are pack and grid.

 Pack

 Grid
 Event Handling

Events in Perl-Tk are handled using callbacks. You can bind events to widgets to respond to user
actions.

 Binding Events

Binding a mouse click event to a label:


 Advanced Widgets

Perl-Tk also provides more advanced widgets like Canvas, Listbox, Text, and Menu.

 Canvas

The canvas widget is used for drawing shapes, text, and images.

 Menu
Creating a menu bar with a file menu:

These examples cover the basics of creating GUIs with Perl-Tk. You can build upon these examples
to create more complex and interactive applications. Perl-Tk provides a powerful way to create
desktop applications with Perl, leveraging the flexibility and simplicity of the Tk toolkit.

You might also like