TCL Notes1
TCL Notes1
TCL Notes1
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.
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,
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(conditional-expression) {
value1 {
# code
}
value1 {
# code
}
...
default {
# code
}
3. For:
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
output
blue green orange red
oA R c P S D| 16 2 89 45 1
(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
1. Command substitution
2. Variable substitution
3. Backslash substitution
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
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.
$ ./backslashsubstitution.tcl
This is my "car"
Set a 10
% put $a
% 10
Arithmetic Operator
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
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
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 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
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
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
If ... statement
Syntax:-
Ex:-
set age 10
Syntax :-
If expression is evaluated to true, then it will return body_1 else it will return
body_2
Ex:--
set age 10
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"
}
}
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
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:-
Syntax:
While {condition} {
Statements
}
Ex :-
#!/usr/bin/tclsh
Set a 10
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
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
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!
#!/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
#!/usr/bin/tclsh
#!/usr/bin/tclsh
Recursive Procedures
An example for recursive procedures is shown below −
Live Demo
#!/usr/bin/tclsh
}
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
Output
1
2
3
4
5
6
7
8
9
10
M o A R c P S D| 16 28 9 45 1
O M oA R c P S D |1 62 89 4 51
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