BASICS OF TCL #
Features of TCL :
- 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.
TCL COMMANDS:
The syntax of Tcl command is as follows:
commandName argument1 argument2 … argumentN
example:
#!/usr/bin/tclsh
puts “Hello, world!”
When the above code is executed, it produces the following result:
Hello, world!
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 [expr 1 + 6 + 9]
When the above code is executed, it produces following result: 16
Variable substitution:
#!/usr/bin/tclsh
set a 3
puts $a
When the above code is executed, it produces the following result: 3
Tcl data types #
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
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
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
Tcl variables #
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
Dynaming variable naming:
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.
Example:
#!/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
Tcl 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 operators
Arithametic oprerators:
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 |
Example:
#!/usr/bin/tclsh
set a 21
set b 10
set c [expr $a + $b]
puts “Line 1 – Value of c is $c\n” set c [expr $a – $b]
puts “Line 2 – Value of c is $c\n” set c [expr $a * $b]
puts “Line 3 – Value of c is $c\n” set c [expr $a / $b]
puts “Line 4 – Value of c is $c\n” set c [expr $a % $b]
puts “Line 5 – Value of c is $c\n”
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 then condition becomes true. | (A == B) is not true. |
!= | Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. | (A != B) is true. |
> | Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. | (A > B) is not true. |
< | Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. | (A < B) is true. |
>= | Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. | (A >= B) is not true. |
<= | Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. | (A <= B) is true. |
Example:
#!/usr/bin/tclsh
set a 21
set b 10
if { $a == $b } {
puts “Line 1 – a is equal to b\n”
} else {
puts “Line 1 – a is not equal to b\n”
}
if { $a < $b } {
puts “Line 2 – a is less than b\n”
} else {
puts “Line 2 – a is not less than b\n”
}
if { $a > $b } {
puts “Line 3 – a is greater than b\n”
} else {
puts “Line 3 – a is not greater than b\n”
}
# Lets change value of a and b set a 5
set b 20
if { $a <= $b } {
puts “Line 4 – a is either less than or equal to b\n”
}
if { $b >= $a } {
puts “Line 5 – b is either greater than or equal to b\n”
}
When you compile and execute the above program it produces the following result:
Line 1 – a is not equal to b
Line 2 – a is not less than b
Line 3 – a is greater than b
Line 4 – a is either less than or equal to -b
Line 5 – b is either greater than or equal to a
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-zero, then condition becomes true. | (A && B) is false. |
|| | Called Logical OR Operator. If any of the two operands is non-zero, then condition becomes true. | (A || B) is true. |
! | Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. | !(A && B) is true. |
Example:
#!/usr/bin/tclsh
set a 5
set b 20
if { $a && $b } {
puts “Line 1 – Condition is true\n”
}
if { $a || $b } {
puts “Line 2 – Condition is true\n”
}
# lets change the value of a and b set a 0
set b 10
if { $a && $b } {
puts “Line 3 – Condition is true\n”
} else {
puts “Line 3 – Condition is not true\n”
}
if { !($a && $b) } {
puts “Line 4 – Condition is true\n”
}
When you compile and execute the above program, it produces the following result:
Line 1 – Condition is true
Line 2 – Condition is true
Line 3 – Condition is not true
Line 4 – Condition is true
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 operands. | (A & B) will give 12, which is 0000 1100 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) will give 61, which is 0011 1101 |
^ | Binary XOR Operator copies the bit if it is set in one operand but not both. | (A ^ B) will give 49, which is 0011 0001 |
<< | Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand. | A << 2 will give 240, which is 1111 0000 |
>> | Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand. | A >> 2 will give 15, which is 0000 1111 |
Example:
#!/usr/bin/tclsh
set a 60 ;# 60 = 0011 1100
set b 13 ;# 13 = 0000 1101
set c [expr $a & $b] ;# 12 = 0000 1100 puts “Line 1 – Value of c is $c\n”
set c [expr $a | $b;] ;# 61 = 0011 1101 puts “Line 2 – Value of c is $c\n”
set c [expr $a ^ $b;] ;# 49 = 0011 0001 puts “Line 3 – Value of c is $c\n”
set c [expr $a << 2] ;# 240 = 1111 0000 puts “Line 4 – Value of c is $c\n”
set c [expr $a >> 2] ;# 15 = 0000 1111 puts “Line 5 – Value of c is $c\n”
When you compile and execute the above program, it produces the following result:
Line 1 – Value of c is 12
Line 2 – Value of c is 61
Line 3 – Value of c is 49
Line 4 – Value of c is 240
Line 5 – Value of c is 15
Ternary operator:
Operator | Description | Example |
? : | Ternary | If Condition is true? Then value X : Otherwise value Y |
Example:
#!/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
TCL decisions #
Tcl language provides following types of decision making statements:
Statement | Description |
if statement | An ‘if’ statement consists of a Boolean expression followed by one or more statements. |
if…else statement | An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the Boolean expression is false. |
nested if statements | You can use one ‘if’ or ‘else’ if statement inside another ‘if’ or ‘else’ if statement(s). |
switch statement | A switch statement allows a variable to be tested for equality against a list of values. |
nested switch statements | You can use one switch statement inside another switch statement(s). |
Tcl-if statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax:
if {boolean_expression} {
# statement(s) will execute if the Boolean expression is true
}
If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If Boolean expression evaluates to false, then the first set of code after the end of the ‘if’ statement (after the closing curly brace) will be executed.
Flow Diagram:
Example:
#!/usr/bin/tclsh
set a 100
#check the boolean condition if {$a < 20 } {
#if condition is true then print the following puts “a is less than 20”
} else {
#if condition is false then print the following puts “a is not less than 20”
}
puts “value of a is : $a”
When the above code is compiled and executed, it produces the following result:
a is not less than 20;
value of a is : 100
if elseif else statement:
An ‘if’ statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement.
When using if, else if, else statements there are few points to keep in mind:
An ‘if’ can have zero or one else’s and it must come after any else if’s.
An ‘if’ can have zero to many else if’s and they must come before the else.
Once an ‘else if’ succeeds, none of the remaining else if’s or else’s will be tested.
Syntax:
if {boolean_expression 1} {
# Executes when the boolean expression 1 is true
} elseif {boolean_expression 2} {
# Executes when the boolean expression 2 is true
} elseif {boolean_expression 3} {
# Executes when the boolean expression 3 is true
} else {
# executes when the none of the above condition is true
}
Example:
#!/usr/bin/tclsh
set a 100
#check the boolean condition if { $a == 10 } {
# if condition is true then print the following puts “Value of a is 10”
} elseif { $a == 20 } {
# if else if condition is true puts “Value of a is 20”
} elseif { $a == 30 } {
# if else if condition is true puts “Value of a is 30”
} else {
# if none of the conditions is true puts “None of the values is matching”
}
puts “Exact value of a is: $a”
When the above code is compiled and executed, it produces the following result:
None of the values is matching Exact value of a is: 100
Tcl -nested if statement:
It is always legal in Tcl to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s).
Syntax:
if { boolean_expression 1 } {
# Executes when the boolean expression 1 is true if {boolean_expression 2} {
# Executes when the boolean expression 2 is true
}
}
You can nest else if…else in the similar way as you have nested if statement.
Example:
#!/usr/bin/tclsh
set a 100
set b 200
# check the boolean condition if { $a == 100 } {
# if condition is true then check the following if { $b == 200 } {
#if condition is true then print the following puts “Value of a is 100 and b is 200”
}
}
puts “Exact value of a is : $a” puts “Exact value of b is : $b”
When the above code is compiled and executed, it produces the following result:
Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200
Tcl – Switch Statement:
A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
Syntax
switch switchingString matchString1 {body1} matchString2 {body2} … matchStringn {bodyn}
The syntax for unquoted switch statement in Tcl language is as follows:
switch switchingString { matchString1 {
body1
}
matchString2 { body2
}
…
matchStringn { bodyn
}
}
The following rules apply to a switch statement:
The switchingString is used in a switch statement; used between the different blocks by comparing to the matchString.
You can have any number of matchString blocks within a switch.
A switch statement can have an optional default block, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true.
Flow Diagram:
Example:
#!/usr/bin/tclsh
set grade C;
switch $grade A { puts “Well done!” } B { puts “Excellent!” } C { puts “You passed!” } F { puts “Better try again” } default { puts “Invalid grade” }
puts “Your grade is $grade”
When the above code is compiled and executed, it produces the following result:
You passed!
Your grade is C
Nested switch statement:
Syntax:
switch switchingString { matchString1 {
body1
switch switchingString { matchString1 {
body1
}
matchString2 { body2
}
…
matchStringn { bodyn
}
}
}
matchString2 { body2
}
…
matchStringn { bodyn
}
}
Example:
#!/usr/bin/tclsh
set a 100
set b 200
switch $a {
100 {
puts “This is part of outer switch” switch $b {
200 {
puts “This is part of inner switch!”
}
}
}
}
puts “Exact value of a is : $a” puts “Exact value of a is : $b”
When the above code is compiled and executed, it produces the following result:
This is part of outer switch This is part of inner switch! Exact value of a is : 100 Exact value of a is : 200
TCL -loops #
Tcl language provides the following types of loops to handle looping requirements.
Loop Type | Description |
while loop | Repeats a statement or group of statements while a given condition is true. It tests the condition before executing the loop body. |
for loop | Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable. |
nested loops | You can use one or more loop inside any another while, for or do..while loop. |
Tcl – while loop:
Syntax
The syntax of a while loop in Tcl language is:
while {condition} { statement(s)
}
Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any nonzero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the loop.
Flow Diagram:
The point to note about the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.
Example:
#!/usr/bin/tclsh
set a 10
#while loop execution while { $a < 20 } {
puts “value of a: $a” incr a
}
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
TCL -for loops:
Syntax
The syntax of a for loop in Tcl language is:
for {initialization} {condition} {increment} { statement(s);
}
Example:
#!/usr/bin/tclsh
# for loop execution
for { set a 10} {$a < 20} {incr a} { puts “value of a: $a”
}
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15 value of a: 16 value of a: 17 value of a: 18 value of a: 19
tcl -nested loop:
Syntax
for {initialization} {condition} {increment} { for {initialization} {condition} {increment} {
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in Tcl language is as follows:
while {condition} { while {condition} {
statement(s);
}
statement(s);
}
Example:
The following program uses a nested for loop to find the prime numbers from 2 to 100:
#!/usr/bin/tclsh
set j 0;
for {set i 2} {$i<100} {incr i} {
for {set j 2} {$j <= [expr $i/$j] } {incr j} { if { [expr $i%$j] == 0 } {
break
}
}
if {$j >[expr $i/$j] } { puts “$i is prime”
}
}
Example:
When the above code is compiled and executed, it produces the following result:
2 | is | prime |
3 | is | prime |
5 | is | prime |
7 | is | prime |
11 | is | prime |
13 | is | prime |
17 | is | prime |
19 | is | prime |
23 | is | prime |
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.
Control Statement | Description |
break statement | Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch. |
continue statement | Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. |
Tcl – break statement:
Syntax
The syntax for a break statement in Tcl is as follows:
Break;
Flow Diagram
Example:
#!/usr/bin/tclsh
set a 10
# while loop execution while {$a < 20 } {
puts “value of a: $a” incr a
if { $a > 15} {
# terminate the loop using break statement break
}
}
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 15
continue statement:
Syntax
The syntax for a continue statement in Tcl is as follows:
Continue;
Flow Diagram
Example:
#!/usr/bin/tclsh
set a 10
# do loop execution while { $a < 20 } { if { $a == 15} {
#skip the iteration incr a
continue
}
puts “value of a: $a” incr a
}
When the above code is compiled and executed, it produces the following result:
value of a: 10 value of a: 11 value of a: 12 value of a: 13 value of a: 14 value of a: 16 value of a: 17 value of a: 18 value of a: 19
tcl -arrays:
set ArrayName(Index) value
example:
#!/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:
Syntax:
[array size variablename]
Example:
#!/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.
Example:
#!/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
Assoviate array:
example:
#!/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:
Syntax:
[array names variablename]
Example:
#!/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
Tcl -lists:
Creating list:
Syntax:
set listName { item1 item2 item3 .. itemn } # or
set listName [list item1 item2 item3] # or
set listName [split “items separated by a character” split_character]
example:
#!/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
result:
red green blue red green blue red green blue
appending item to list:
syntax:
append listName split_character value # or
lappend listName value
example:
#!/usr/bin/tclsh
set var orange append var ” ” “blue” lappend var “red” lappend var “green” puts $var
result:
orange blue red green
length of list:
syntax: llength listName
example:
#!/usr/bin/tclsh
set var {orange blue red green} puts [llength $var]
result:
4
List item at index:
Syntax:
lindex listname index
example: #!/usr/bin/tclsh
set var {orange blue red green} puts [lindex $var 1]
result:
blue
insert item at index:
syntax:
linsert listname index value1 value2..valuen
example:
#!/usr/bin/tclsh
set var {orange blue red green}
set var [linsert $var 3 black white] puts $var
result: orange blue red black white green
replace item at indices:
syntax:
lreplace listname firstindex lastindex value1 value2..valuen
example:
#!/usr/bin/tclsh
set var {orange blue red green}
set var [lreplace $var 2 3 black white] puts $var
result:
orange blue black white
sorting list:
syntax:
lsort listname
example:
#!/usr/bin/tclsh
set var {orange blue red green} set var [lsort $var]
puts $var
result: blue green orange red
TCL -procedures:
Syntax: proc procedureName {arguments} { body
}
Example:
#!/usr/bin/tclsh
proc helloWorld {} { puts “Hello, World!”
}
helloWorld
result: Hello, World!
Procedures with multilple arguments:
Example:
#!/usr/bin/tclsh
proc add {a b} { return [expr $a+$b]
}
puts [add 10 30]
result: 40
procedures with variable arguments:
example:
#!/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 }]
result: 65 66
Tcl -FILE I/O :
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 FILE:
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:
Mode | Description |
r | 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 | Opens a text file for writing, if it does not exist, then a new file is created else existing file is truncated. |
a | 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. |
r+ | Opens a text file for reading and writing both. File must exist already. |
w+ | 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+ | 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 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 file:
Puts command is used to write to an open file.
Syntax: puts $filename “text to write”
Example:
#!/usr/bin/tclsh
set fp [open “input.txt” w+] puts $fp “test”
close $fp
result:
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 file:
Syntax:
set file_data [read $fp]
example:
#!/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