TCL TK Tutorial: Tool Command Language

What is TCL?

TCL is shell application that reads TCL command from its standard input or from a file and gives desired results.

TCL is string based scripting language and also a procedural language. It was first created by John Osterhout in 1989. The purpose of developing this language is easy embedded inti ( ) applications. The language is commonly used for GUIs and testing. For instance, rapid prototyping, Testing database interaction, etc. In TCL by default everything is a string.

In this tutorial, you will learn-

How to Execute TCL

There are two ways to execute TCL code

  1. Windows based application is available here tcltutor exe file
  2. Linux based application

In Linux interactive interpreter, we can execute the TCL scripts as below

To access TCL interactive session, execute the following command

TCL Tutorial: Tool Command Language

TCL scripts

TCL program should have a .tcl extension. Every script in UNIX/LINUX starts with TCL shell path

#!/usr/bin/tclsh

Example:-

#!/usr/bin/tclsh
Puts "Hello World"
Script execution:-
$ chmod +x helloworld.tcl
$ ./helloworld.tcl

Output: Hello World

In TCL, “Puts” Command is used to print messages to the console .syntax of puts is below

puts?-nonewline? ?channelId? string

  • Nonewline: This optional parameter suppresses the newline character by default command. It puts a newline to each string
  • Channelid: This parameter used for standard input channel (stdin) and standard output channel (stdout).

Ex:-

%puts "Hello World"
% Hello World
%puts stdout  "Hello World"
% Hello World

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:-

#!/usr/bin/tclsh
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

#!/usr/bin/tclsh

puts "This  is my  \"car\"

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

NOTE: –To comment any string in TCL “#” is used. All characters after the “#” are ignored by tclsh shell command.

TCL Variable

A variable is an identifier which holds a value. In other words, a variable is a reference to a computer memory, where the value is stored.

Variables are created by “set command” and all variable names are case sensitive. It means hello, Hello, HELLO all are different in TCL. Look at some example for case sensitive variable.

% set  name  Techoit
% set  Name  Technoit_1
% set  NAME  Technoit_2

Output:-

% puts $name
% Technoit

%puts  $Name
%Technoit_1

%puts $NAME
%Technoit_2

Creating TCL Variables

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 Command Info exist

The “set” command is used to create and read variables as shown above. The unset command is used to destroy a variable. The “info exists” command returns 1 if varName exists as a variable (or an array element) in the current context, otherwise returns 0. ( see example below).

There are various “info” command in TCL like “info exists”, “info functions”, “info global”, and so on. Here we will see an example of “info exists”.

Ex:-

% set a 20
% puts $a
% 20
% puts [info exists a]
% 1
% unset a
%puts [info exists a]
% 0

Different braces and their behaviour

{} -> Curly braces

Curly braces in TCL group words together to become arguments. Curly braces are used to define a block that’s deferred – in other words, it may be run AFTER the rest of the command on the current line. Characters within braces are passed to a command exactly as written.

Some points to remember

  1. Variable substitution is not allowed inside {} braces
  2. It used to create list data type

Example:-

% set x 10
% puts {$x}
% $x

%set number {1 2 3 4 5} -> Here number is a list data type

%puts $number

%1 2 3 4 5

[] -> 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.

Ex: –

% 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

For print “Nth” value of array a, we will use Puts $a(N)

TCL Command-line arguments

Items of data passed to a script from the command line are known as arguments. The number of command line arguments to a Tcl script is passed as the global variable argc . The name of a Tcl script is passed to the script as the global variable argv0 , and the rest of the command line arguments are passed as a list in argv.

TCL has 3 pre-defined variables such as

$argc   -> indicates the number of arguments passed to the script

$argv   -> indicates list of arguments

$argv0  -> indicates the name of script

Ex:–

arg-script.tcl
#!/usr/bin/tclsh<
puts   "number of arguments passed to the scripts : $argc"
puts  "list of arguments are passed to the script: $argv"
puts  "the name of scripts is: $argv0"
$ ./arg-script.tcl  10 20 30

output:-

  • Number of arguments passed to the scripts: 3
  • List of arguments are passed to the script: 10 20 30
  • The name of the script is : arg-script.tcl

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/Associativity
Arithmetic Operator + - * / % Left to Right
Relational Operator == != < > <= >= Left to Right
Logical Operator && || ! Left to Right
Bitwise Operator & | ^ ~ Left to Right
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

Bitwise Operator

& (bitwise and) perform bit by bit operation and follow the below table for operation.

A B A & B
0 0 0
0 1 0
1 1 1
1 0 0

Ex:-

%set A 10
%set B 20

Follow the sequence to convert decimal to binary number
128 64 32 16 8 4 2 1
10 binary equivalents will be  
128 64 32 16 8 4 2 1  à  0 0 0 0 1 0 1 0
20 binary equivalents will be 
128 64 32 16 8 4 2 1  à  0 0 0 1 0 1 0 0

So now as per above tabular rules

A & B will be 0 0 0 0 0 0 0 0 

| (bitwise or) perform bit by bit operation and follow the below table

A B A | B
0 0 0
0 1 1
1 1 1
1 0 1

Ex:-

%set A 10
%set B 20

Follow the sequence to convert decimal to binary number
128 64 32 16 8 4 2 1
10 binary equivalents will be  
128 64 32 16 8 4 2 1  à  0 0 0 0 1 0 1 0
20 binary equivalents will be 
128 64 32 16 8 4 2 1  à  0 0 0 1 0 1 0 0

So now as per above tabular rules

A | B will be 0 0 0 1 1 1 1 0 

^ (bitwise exclusive or) perform bit by bit operation and follow the below table

A B A ^ B
0 0 0
0 1 1
1 1 0
1 0 1

Ex:-

%set A 10
%set B 20

Follow the sequence to convert decimal to binary number
128 64 32 16 8 4 2 1
10 binary equivalents will be  
128 64 32 16 8 4 2 1  à  0 0 0 0 1 0 1 0
20 binary equivalents will be 
128 64 32 16 8 4 2 1  à  0 0 0 1 0 1 0 0

So now as per above tabular rules

A ^ B will be 0 0 0 1 1 1 1 0 à 30

~ (bitwise negation) operator changes each 1 to 0 and 0 to 1, follow the table as reference

A ~A
0 1
1 0
%set A 7
%puts [expr ~$A]
-8

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

Shift Operator

Shift operator is denoted by either << left shift operator, or by the >> right shift operator. For << left shift operator, the left operands value is moved left by the number of bits specified by the right operand.

%set A 7
%set result [expr $A << 2]
%puts $result

For the >> right shift operator, the left operands value is moved right by the number of bits specified by the right operand.

%set A 7
%set result [expr $A >> 2]
%puts $result

String Comparison Operator

String comparison operator compares the value of both operands. If the value of operand are same, then it will return 1 else return 0. In example value for both A and B is 7, therefore result return 1.

Ex:-

%set A 7 
%set B 7
%set result [expr $A eq $B]
%puts $result
1

Ne (if value of both operand are different then it will return 1 else return 0)

%set A 7 
%set B 8
%set result [expr $A ne $B]
%puts $result
1

Exponentiation operator

Pow () and ** both are same. It always returns floating value.

** indicates the power to the desired operand.

Ex:-

%set A 7
%set result [expr $A ** 2]
%puts $result
49

List Operator

If the required value found in the defined list, it returns 1 else return 0. In example value 1 exists in variable 'a' hence it will return 1.

set a {1 2 3}
if {1 in $a} {
puts "ok"
} else {
puts "fail"
}
Output: ok

ni, if the required value found in the defined list then it will return 0 else return 1.

Ex :-

set a {1 2 3}
if {1 ni $a} {
puts "ok"
} else {
puts "fail"
}
Output: fail

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

Summary:

  • TCL is string based scripting language and also a procedural language
  • The language is commonly used for GUIs and testing
  • In TCL by default everything is string
  • TCL is shell application that reads TCL command from its standard input or from a file and gives desired results.
  • TCL program should have .tcl extension