TCL Notes1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

What is TCL?

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.

In TCL by default everything is a string.

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.

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.
Variables
Variable is a identifier which is used to hold the value. set is used to create variables.

Examples
set name onecompiler

Loops
1. If-Else:

When ever you want to perform a set of operations based on a condition IF-ELSE is used.

if(conditional-expression) {
#code
} else {
#code
}

You can also use if-else for nested Ifs and If-Else-If ladder when multiple conditions are to be
performed on a single variable.

2. Switch:

Switch is an alternative to If-Else-If ladder.

switch(conditional-expression) {
value1 {
# code
}
value1 {
# code
}
...
default {
# code
}

3. For:

For loop is used to iterate a set of statements based on a condition.

for{start}{test}{next}{
# code
}
4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred
when number of iterations are not known in advance.

while(condition) {
# code
}

Arrays
Array is a collection of similar data which is stored in continuous memory addresses. Array
values can be fetched using index. Index starts from 0 to size-1.

Syntax
set ArrayName(Index) value

Procedures
Procedure is a sub-routine which contains set of statements. Uusually procedures are required
when multiple calls are made to same set of statements. Procedures increases re-usuability and
modularity.

Syntax
proc procedureName {arguments} {
# code
}
1. Write a TCL script to find the factorial of a
number
set counter 4
set factorial 1
while {$counter > 0} {
set factorial [expr $factorial * $counter]
incr counter -1
}
puts $factorial

Factorial 10
=> 3628800
O M oA R c P S D |1 62 89 4 51
2. Write a TCL script that multiplies the numbers from
1 to 10
set n 10
for {set i 1} {$i <= $n} {incr i} {
puts $i
}

Output
1
2
3
4
5
6
7
8
9
10
oA R c P S D| 16 2 89 45 1

3. Write a TCL script for Sorting a list using a comparison


function
The syntax for sorting a list is given below -
lsort listname
An example for sorting a list is given below -

set var {orange blue red green}


set var [lsort $var]
puts $var

output
blue green orange red
oA R c P S D| 16 2 89 45 1

14. Write a TCL script to

(i)create a list
(ii )append elements to the list
(iii)Traverse the list
(iv)Concatenate the list

Creating a List
Some examples are given below -
set colorList1 {red green blue}
set colorList2 [list red green blue]
set colorList3 [split "red_green_blue" ]
puts $colorList1
puts $colorList2
puts $colorList3
result -
red green blue
red green blue
red green blue
Appending Item to a List
Some examples are given below -
set var orange
append var " " "blue"
puts $var
result -
orange blue

Traversing lists
foreach item {1 2 3 4 5 6 7 8 9} {
puts $item
}

result -
1
2
3
4
5
O M oA R c P S D |1 62 89 4 51
6
7
8
9

Concatenate the list


set i [concat {a b c} {1 2 3}]
puts $i
result -
abc123
R c P S D| 16 28 9 45 1

5. Write a TCL script to comparing the file modified


times.

proc newer { fp fp2 } {


if ![file exists $fp] {
puts "file exsist"
} else {
# Assume file1 exists
expr [file mtime $fp] > [file mtime $fp2]
puts "file modification times compared."
}
}
newer for.tcl foreach.tcl

6. Write a TCL script to Copy a file and translate to


native format.
proc Sree {src dest} {
set in [open $src]
set out [open $dest w]
puts -nonewline $out [read $in]
close $out ; close $in
}
TCL scripts
TCL program should have a .tcl extension.
TCL Substitution type
There are three kinds of substitutions in TCL

1. Command substitution
2. Variable substitution
3. Backslash substitution

Let‟s study one by one

Command substitution

Square brackets are used for command substitution.

Example:-
% puts [expr 1*3]
% 3
Here the command between the square brackets is evaluated first. The results
is returned .”expr” used for performing the arithmetic calculation.

Variable substitution

TCL performs variable substitution with the help of $ sign.

Example:-
set a 10
puts a
puts $a
Here we create a variable called “a” and set value “10” to it.

 puts a : It will print string “a” but not the value of „a‟ to the console
 puts $a : It will print the value of „a‟ to the console

Let‟s execute and verify it. You will get the output as below.
$ ./substitution.tcl
a

10

Backslash substitution
In Tcl, the backslash is used for escaping special characters as well as for
spreading long commands across multiple lines. Any character immediately
following the backslash will stand without substitution. In the example below,
you can see special character ” “, remains after the backslash.

Let‟s verify this with an example

puts "This is my \"car\"

$ ./backslashsubstitution.tcl
This is my "car"

To create variables in TCL, you need to use “set” command

Set a 10

To obtain the value of variable have to use “$” symbol like

% put $a

% 10

So we get the value of variable „a‟ as 10.

TCL Expression and Operator


Expression is constructed from operands and operators. It's evaluated with
"expr" command. Operators are evaluated based on precedence and
associativity. TCL language has built-in operators as below

Operator Category Symbol Precedence/Asso

Arithmetic Operator +-*/% Left to Right

Relational Operator == != < > <= >= Left to Right

Logical Operator && || ! Left to Right

Bitwise Operator &|^~ Left to Right


Operator Category Symbol Precedence/Asso

Ternary Operator ?: Right to Left

Shift Operator << >> Left to Right

String Comparison Operator eq ne Left to Right

Exponentiation Operator ** Left to Right

List Operator In ni Left to Right

Arithmetic Operator

A TCL expression consists of a combination of operands, operators, and


parentheses. Let see example of Arithmetic operators in TCL

+ Add two or more operands

Ex:-
%set a 10
%set b 20
%puts [expr $a + $b]
30
- Subtracts two or more operands

Ex:-
%set a 20
%set b 10
%puts [expr $a - $b]
10
*Multiply two or more operands
%set a 20
%set b 10
%puts [expr $a * $b]
200
/ Divide numerator by denumerator
%set a 20
%set b 10
%puts [expr $a / $b]
2
% Modulus operator divides numerator by de-numerator but returns reminder
%set a 20
%set b 10
%puts [expr $a % $b]
0
Relational Operator

Checks if the value of left operand is greater than the value of the right
operand. If yes, then condition becomes true and return 1 else return 0.
%set a 20
%set b 10
%puts [expr $a > $b]
1
Check if the value of left operand is less than the value of the right operand. If
yes, then condition becomes true and return 1 else return 0
%set a 10
%set b 20
%puts [expr $a < $b]
1
>= Checks if the value of left operand is greater than or equal to the value of
right operand, if yes then condition becomes true and return 1 else return 0
%set a 20
%set b 10
%puts [expr $a >= $b]
1
<= Checks if the value of left operand is less than or equal to the value of right
operand, if yes then condition becomes true and return 1 else return 0
%set a 20
%set b 10
%puts [expr $a <= $b]
0
!= Checks if the values of two operands are equal or not, if values are not
equal then condition becomes true and return 1 else return 0
%set a 20
%set b 10
%puts [expr $a != $b]
1
== Checks if the values of two operands are equal or not, if yes then condition
becomes true and return 1 else return 0
%set a 20
%set b 10
%puts [expr $a == $b]
0
Logical Operator
&& If both the operands are non-zero, then condition becomes true and return
1 else return 0
%set a 20
%set b 10
%puts [expr $a && $b]
1
|| If any of the two operands is non-zero, then condition becomes true and
return 1 else return 0
%set a 0
%set b 10
%puts [expr $a || $b]
1
! Used to reverse the result of any expression. Here in the output, you can see
the value of 'a' has now become 1 from 0. While the value of 'b' has become 0
from 1.
%set a 0
%set b 1
%puts [expr !$a]
1
%puts [expr !$b]
0

Ternary Operator ( ?:)

Syntax is
condition-expression? expression_1: expression_2
If condition-exp is true, exp1 is evaluated and the result is returned. If the
cond-exp is false, exp2 is evaluated and its result is returned. In our example,
exp1 is true as the value of A is greater than 6.
%set A 7
%set result [expr $A > 6 ? true : false]
%puts $result
true
Ternary Operator ( ?:)

Syntax is
condition-expression? expression_1: expression_2
If condition-exp is true, exp1 is evaluated and the result is returned. If the
cond-exp is false, exp2 is evaluated and its result is returned. In our example,
exp1 is true as the value of A is greater than 6.
%set A 7
%set result [expr $A > 6 ? true : false]
%puts $result
true

Ternary Operator ( ?:)

Syntax is
condition-expression? expression_1: expression_2
If condition-exp is true, exp1 is evaluated and the result is returned. If the
cond-exp is false, exp2 is evaluated and its result is returned. In our example,
exp1 is true as the value of A is greater than 6.
%set A 7
%set result [expr $A > 6 ? true : false]
%puts $result
true

[] -> square braces

Square brackets are used to create nested command. Simply put, output of
one command passed as argument to another command. Square brackets
are used to define a block that‟s run BEFORE the rest of the command on the
current line, and the result is substituted into the line.
% set x 10
% puts "y : [set y [set x 10]]"
%y : 10
% puts "x : $x"
%x : 10

() -> round braces

This command is used to create array data type and also indicate operator
precedence.
% set a(1) 10
% set a(2) 20
Here “a” is an array with value 10 and 20. See below commands to print keys,
key value pairs and values of array.
% puts [array get a] -> To print key value pairs we use this command
% 1 10 2 20
% puts [array names a] -> To print only keys
% 1 2
% puts $a(1) -> To print first value of array
% 10
% puts $a(2) -> To print second value of array
% 20

() -> round braces

This command is used to create array data type and also indicate operator
precedence.
% set a(1) 10
% set a(2) 20
Here “a” is an array with value 10 and 20. See below commands to print keys,
key value pairs and values of array.
% puts [array get a] -> To print key value pairs we use this command
% 1 10 2 20
% puts [array names a] -> To print only keys
% 1 2
% puts $a(1) -> To print first value of array
% 10
% puts $a(2) -> To print second value of array
% 20

TCL flow control and decision making


There are various flow control and decision making command which are used
to alter the flow of a program. Program executions always start from the top of
source file to the bottom.

If statement consists of Boolean expression followed by one or more


statements.

If ... statement

Syntax:-

if expr ?then? body

if expr is evaluated to true, then the body of command is executed.

Ex:-
set age 10

if {$age < 20} {


puts "Age is less than 20"
}

Output: Age is less than 20


If ... else statement

Syntax :-

If expression ? then body_1 else body_2

If expression is evaluated to true, then it will return body_1 else it will return
body_2

Ex:--
set age 10

if {$age < 20} {


puts "Age is less than 20"
} else {
Puts "Age is greater than 20"
}

output: Age is less than 20


Nested if..else statement

It means one if or else..if statement can be put inside another if or else..if


statements.

Syntax:-
If {expression_1} {
Body_1
If {expression_2} {
Body_2
}
}
Ex:--
set a 10
set b 20

if {$a == 10} {
# if expression_1 is true then it will go to expression_2
if {$b == 20} {
#if expression_2 is true then it will print the below string
puts "value of a is 10 and b is 20"
}
}

o/p: value of a is 10 and b is 20


Switch statement

The switch statement enables a variable to be tested for equality against a list
of values. It evaluates the list of values and returns the result of that
evaluation. If no values matches then default values will be returned.

Example:
#!/usr/bin/tclsh

# switch_cmd.tcl

set domain x
switch $domain {

x { puts "x" }
y { puts "y" }
z { puts "z" }
default { puts "unknown" }
}
Nested switch

Nested switch statement means switch statement inside a switch statement.

Syntax :-
switch <switchingstring1> {
<matchstring1> {
body1
switch <switchingstring2> {
<matchstring2> {
body2
}
...
switch <switchingstringN> {
<matchStringN> {
bodyN
}
}
}
Example: In the following example, value of a is 100, and with the same code
we switch statement for another value of b is 200. The out will show value for
both a and b.
#!/usr/bin/tclsh

set a 100
set b 200

switch $a {
100 {
puts "The value of a is $a"
switch $b {
200 {
puts "The value of b is $b"
}
}
}
}
Output:-

The value of a is 100

The value of b is 200

TCL Loop statement

Loop statement allows executing a statement or group of statement multiple


times. Tcl provides the following types of looping statement.
While command

When a given condition is true then a statement or group of statement repeats


which are in the loop body.

Syntax:
While {condition} {
Statements
}
Ex :-
#!/usr/bin/tclsh

Set a 10

While {$a < 12} {


Puts "a is $a"
incr a
}
Output:-

a is 10

a is 11

In the above example, "incr" built-in command is used. It means the value of
'a' will be increased by 1 till the maximum value (<12).

For command

It executes a sequence of statements multiple times based upon a counter


value. It is automatically increased or decreased during each repetition of the
loop.

Syntax :-
For {start} {test} {next} {
Body
}
Example: In below example value of 'i' is set to 0 and incremented till value
<5.
#!/usr/bin/tclsh

for {set i 0} {$i < 5} {incr i} {


put $i
}
Output:-
0
1
2
3
4

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 −
Live Demo

#!/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 −
Live Demo

#!/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 −
Live Demo

#!/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 −
Live Demo

#!/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 −
Live Demo

#!/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
11. Write a TCL script to find the factorial of a
number
set counter 4
set factorial 1
while {$counter > 0} {
set factorial [expr $factorial * $counter]
incr counter -1
}
puts $factorial

Factorial 10
=> 3628800
lO M oA R c P S D| 1 62 89 45 1

12. Write a TCL script that multiplies the numbers from


1 to 10
set n 10
for {set i 1} {$i <= $n} {incr i} {
puts $i
}

Output
1
2
3
4
5
6
7
8
9
10
M o A R c P S D| 16 28 9 45 1

13. Write a TCL script for Sorting a list using a comparison


function
The syntax for sorting a list is given below -
lsort listname
An example for sorting a list is given below -

set var {orange blue red green}


set var [lsort $var]
puts $var
output
blue green orange red

O M oA R c P S D |1 62 89 4 51

14. Write a TCL script to


(i)create a list
(ii )append elements to the list
(iii)Traverse the list
(iv)Concatenate the list

Creating a List
Some examples are given below -
set colorList1 {red green blue}
set colorList2 [list red green blue]
set colorList3 [split "red_green_blue" ]
puts $colorList1
puts $colorList2
puts $colorList3
result -
red green blue
red green blue
red green blue
Appending Item to a List
Some examples are given below -
set var orange
append var " " "blue"
puts $var
result -
orange blue

Traversing lists
foreach item {1 2 3 4 5 6 7 8 9} {
puts $item
}

result -
1
2
3
4
5
O M oA R c P S D |1 62 89 4 51

6
7
8
9
Concatenate the list
set i [concat {a b c} {1 2 3}]
puts $i
result -
abc123
O M oA R c P S D |1 62 89 4 51

15. Write a TCL script to comparing the file modified


times.

proc newer { fp fp2 } {


if ![file exists $fp] {
puts "file exsist"
} else {
# Assume file1 exists
expr [file mtime $fp] > [file mtime $fp2]
puts "file modification times compared."
}
}
newer file1.txt file2.txt

You might also like