0% found this document useful (0 votes)
6 views13 pages

TCL TK

The document provides an introduction to Tcl programming, covering basic syntax, comments, identifiers, whitespace, commands, and variable handling. It explains how to create a simple Tcl program, the structure of commands, and various types of operators and decision-making statements. Additionally, it discusses dynamic typing, mathematical expressions, and operator precedence in Tcl.

Uploaded by

practicesiva1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

TCL TK

The document provides an introduction to Tcl programming, covering basic syntax, comments, identifiers, whitespace, commands, and variable handling. It explains how to create a simple Tcl program, the structure of commands, and various types of operators and decision-making statements. Additionally, it discusses dynamic typing, mathematical expressions, and operator precedence in Tcl.

Uploaded by

practicesiva1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Tcl - Basic Syntax

Tcl is quite simple to learn and let's start creating our first Tcl program!

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 −

$ tclsh test.tcl

We will get the following output −

Hello, World!

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 −

Hello World!

Multiline or block comment is written using 'if' with condition '0'. An example is shown below.

#!/usr/bin/tclsh

if 0 {

my first program in Tcl program

Its very simple

puts "Hello World!"

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

Hello World!

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

#!/usr/bin/tclsh
puts "Hello World!" ;# my first print in Tcl program

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

Hello World!

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 −

mohd zara abc move_name a_123

myname50 _temp j a23b9 retVal

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 [expr 3 + 2] ;# print sum of the 3 and 2

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.

Tcl - Commands
As you know, 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 −

commandName argument1 argument2 ... argumentN

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 −

Hello, world!

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

puts stdout "Hello, world!"

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

Hello, world!

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 [expr 1 + 6 + 9]

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

16

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 −

Hello

World

Tcl - Variables
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.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

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 Operator

This chapter will explain the arithmetic, relational, logical, bitwise, and ternary operators one
by one.

Arithmetic Operators

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

Operato Description Example


r
+ 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 B % A will give 0
integer division

Relational Operators

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

Operat Description Example


or
== Checks if the values of two operands are equal or (A == B) is not true.
not, if yes then condition becomes true.
!= Checks if the values of two operands are equal or (A != B) is true.
not, if values are not equal then condition
becomes true.
> Checks if the value of left operand is greater than (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 (A < B) is true.
the value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater than (A >= B) is not true.
or equal to the value of right operand, if yes then
condition becomes true.
<= Checks if the value of left operand is less than or (A <= B) is true.
equal to the 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 −

Operat Description Example


or
&& Called Logical AND operator. If both the operands (A && B) is false.
are non-zero, then condition becomes true.
|| Called Logical OR Operator. If any of the two (A || B) is true.
operands is non-zero, then condition becomes
true.
! Called Logical NOT Operator. Use to reverses the !(A && B) is true.
logical state of its operand. If a condition is true
then Logical NOT operator 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 −

Operat Description Example


or
& Binary AND Operator copies a bit to the result if (A & B) will give 12, which is
it exists in both operands. 0000 1100
| Binary OR Operator copies a bit if it exists in (A | B) will give 61, which is
either operand. 0011 1101
^ Binary XOR Operator copies the bit if it is set in (A ^ B) will give 49, which is
one operand but not both. 0011 0001
<< Binary Left Shift Operator. The left operands A << 2 will give 240, which is
value is moved left by the number of bits 1111 0000
specified by the right operand.
>> Binary Right Shift Operator. The left operands A >> 2 will give 15, which is
value is moved right by the number of bits 0000 1111
specified by the right operand.
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

Tcl - Decisions
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.N Statement & Description


o.
1 if statement
An 'if' statement consists of a Boolean expression followed by one or more
statements.
2 if...else statement
An 'if' statement can be followed by an optional 'else' statement, which executes
when the Boolean expression is false.
3 nested if statements
You can use one 'if' or 'else if' statement inside another 'if' or 'else if' statement(s).
4 switch statement
A switch statement allows a variable to be tested for equality against a list of
values.
5 nested switch statements
You can use one switch statement inside another switch statement(s).
The ? : Operator

We have covered conditional operator ? : in previous chapter, 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

Tcl - Loops
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.N Loop Type & Description


o.
1 while loop
Repeats a statement or group of statements while a given condition is true. It tests
the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
3 nested loops
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.N Control Statement & Description


o.
1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.
2 continue statement
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.

Tcl - Arrays
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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy