TCL Scripting
TCL Scripting
Tcl Scripting
Introduction:
▪ Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2, and Mac OSX.
▪ It aims at providing ability for programs to interact with other programs and also for acting as an embeddable
interpreter.
Features of Tcl :
▪ Write once, run anywhere. It runs on Windows, Mac OS X, and almost on every Unix platform
2 vwww.starvlsi.com
▪ 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
▪ Finally, it's an open source, free, and can be used for commercial applications without any limit.
Applications :
▪ Embedded applications.
3 vwww.starvlsi.com
Tcl Interpreter:
Word Grouping
Substitution
Command
Evaluation
Word Grouping
▪ Words can be grouped as using one of the arguments [ Braces {} , Double quotes (“ “) ]
▪ Example : puts {hello} , puts “hello” [puts is used to print the string or group of characters like printf]
4 vwww.starvlsi.com
Substitution
▪ Variable substitution.
▪ Command substitution.
▪ Backslash substitution.
1.Variable Substitution:
▪ In variable substitutions, $ is used before the variable name and this returns the contents of the variable.
puts $a [Here $ is used before the variable name (a) and this returns the contents in the variable.it displays 3 ]
5 vwww.starvlsi.com
2. Command Substitution:
▪ In command substitutions, square brackets are used to evaluate the scripts inside the square brackets .
puts [expr 1 + 6 + 9] output : 16 [Note: Expr is used for evaluating the mathematical Expressions]
3. Backslash Substitution :
6 vwww.starvlsi.com
Example output
Mathematical Expressions :
▪ In order to get floating point results, we should add at least a single decimal digit.
7 vwww.starvlsi.com
Example
output
With precision
output
8 vwww.starvlsi.com
Operators
▪ An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
9 vwww.starvlsi.com
Arithmetic Operators
▪ Let us assume A = 20 , B = 10
Subtraction (-) It subtracts the second operand from the first A-B will give 10
Multiplication (*) It multiplies the both Operands A*B will give 200
Division (/) It divides numerator by denominator ( I,e it will A/B will give 2
give the quotient value)
Modulus (%) It is same as like division but it will give the A%B will give 0
remainder as output
10 vwww.starvlsi.com
Example
oOutput
11 vwww.starvlsi.com
Relational Operators
▪ Let us assume A = 20 , B = 10
Operators Description Example
Equal (= =) checks if the value of two operands are equal or not, (A = = B) is not true
if yes then condition becomes true
Not Equal (! =) checks if the value of two operands are equal or not, (A != B) is true
if values are not equal then condition becomes true
Greater Than ( > ) checks if the value of left Operand is greater than (A > B) is true
the value of right Operand. If yes then condition
becomes true
Less Than ( < ) Checks if the value of left Operand is less than the (A < B) is not true
value of right Operand. If yes then condition
becomes true.
Less Than or Equal to Checks if the value of left Operand is less than or ( A < = B) is not true
(<=) equal to the value of right Operand. If yes then
condition becomes true,
Greater Than or Equal Checcks if the value of left Operand is greater than ( A > = B) is true
12
to vwww.starvlsi.com
or equal to the value of right Operand. If yes then
( > =) condition becomes true
Example 1
output
13 vwww.starvlsi.com
Example (cont..)
output
14 vwww.starvlsi.com
Logical Operators
Logical AND (&&) If both the operands are non-zero, (A&&B) is false
then condition becomes true.
15 vwww.starvlsi.com
Example
outoutput
16 vwww.starvlsi.com
Bitwise Operators
▪ The truth tables for AND,OR,XOR and it is same as logic gates in Digital…
A B A &B A| B A^B
0 0 0 0 0
0 1 0 1 1
1 0 0 1 0
1 1 1 1 1
▪ Assume if A = 15; and B = 13; now in binary format they will be as follows
17 vwww.starvlsi.com
Operators Description Example
Bitwise AND ( &) It copies a bit to the result if it (A & B) will give 13, which is
exists in both operands 0000 1101
Bitwise XOR ( ^ ) Binary XOR Operator copies the (A ^ B) will give 2, which is
bit if it is set in one operand 0000 0010
but not both.
Bitwise Left Shift ( < < ) The left operands value is A << 2 will give 60 , which is
moved left by the number of 0011 1100
bits specified by the right
operand
Bitwise Right Shift ( > > ) The left operands value is A >> 2 will give 3, which is
moved right by the number of 0000 0011
bits specified by the right
operand.
18 vwww.starvlsi.com
Example
boutput
19 vwww.starvlsi.com
Ternary Operator
Example
output
20 vwww.starvlsi.com
Operators Precedence in Tcl
▪ 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
21 vwww.starvlsi.com
Category v Operator Associativity
Unary +- Right to Left
Multiplicative */% Left to Right
Additive +- Left to Right
Shift << >> Left to Right
Relational <<=>>= Left to Right
Equality ==!= 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
22 vwww.starvlsi.com
Example
Output
23 vwww.starvlsi.com
Decision Making Statements
If Statement
Syntax: if {Boolean_expression} {
#statements
}
▪ 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:
24 vwww.starvlsi.com
Example:
output
If else Statement
Syntax: if {boolean_expression} {
#statements will execute if the boolean expression is true.
} else {
#statements will execute if the boolean expression is false.
}
▪ If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of
code will be executed.
25 vwww.starvlsi.com
Flow Diagram :
Example:
output
26 vwww.starvlsi.com
If…else if…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.
▪ 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.
}
27 vwww.starvlsi.com
Example:
output
28 vwww.starvlsi.com
Nested If Statement
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.
}
}
Example:
output
29 vwww.starvlsi.com
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.
▪ 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
switch switchingString {
matchString1 {
body1
}
matchString2 {
body2
}
…..
matchStringn {
bodyn
}
} 30 vwww.starvlsi.com
Example:
output
31 vwww.starvlsi.com
Nested Switch Statement
Syntax:
switch switchingString { Example
matchString1 {
body1
switch switchingString {
matchString1 {
body1
}
matchString2 {
body2
}
…..
matchStringn {
bodyn
}
}
}
….
matchStringn {
bodyn32 vwww.starvlsi.com
}}
output
Loops:
• In general, statements are executed sequentially: The first statement in a function is executed first, followed by the
second, and so on.
• A loop statement allows us to execute a statement or group of statements multiple times.
Types of Loops:
1.While Loop
In while loop, the statement executes repeatedly as long as a given condition is true.
output
34 vwww.starvlsi.com
2. For Loop
Syntax:
#statements;
}
▪ The initialization step is executed first, and only once. This step allows you to declare and initialize any loop
control variable.
▪ Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop
does not execute and flow of control jumps to the next statement just after the for loop.
▪ After the body of the for loop executes, the flow of control jumps back up to the increment statement.
▪ The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop,
then increment step, and then again condition). After the condition becomes false, the for loop terminates.
35 vwww.starvlsi.com
Flow Diagram
Example
output
36 vwww.starvlsi.com
Note: The main difference between for loop and while loop is as shown below.
▪ For loop is used when the number of iterations is known where as while loop is used when
the number of iterations is not known.
3.Nested loop:
▪ In Nested loops, You can use one or more loop inside any another loop.
Syntax for Nested For loop: Syntax for Nested While loop:
▪ A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For
example, a for loop can be inside a while loop or vice versa
37 vwww.starvlsi.com
Example: The following example uses a nested for loop to find the prime numbers from 2 to 20 −
output
38 vwww.starvlsi.com
Loop Control Statements
1.Break:
▪ The break statement is used for terminating a loop.
▪ When the break statement is encountered inside a loop, the loop is immediately terminated.
▪ If you are using nested loops , the break statement will stop the execution of the innermost loop and start executing
the next line of code after the block.
Syntax: break;
39 vwww.starvlsi.com
Example output
2.Continue:
▪ The continue statement in Tcl language works somewhat like the break statement.
▪ Instead of forcing termination, however, continue forces the next iteration of the loop to take place, skipping any
code in between.
Syntax: continue ;
40 vwww.starvlsi.com
Flow Diagram Example
output
41 vwww.starvlsi.com
Infinite Loop:
▪ The while loop is traditionally used for this purpose .You can make an endless loop by leaving the conditional
expression as 1.
Syntax:
while {1} {
puts “This loop will run forever.”
}
▪ Tcl programmers more commonly use the while {1} construct to signify an infinite loop.
vwww.starvlsi.com
42
Arrays
▪ An array is a systematic arrangement of a group of elements using indices.
Size of Array
43 vwww.starvlsi.com
Array Iteration
▪ If the array indices are continuous then we can use array iteration to access elements of the array.
▪ A simple array iteration for printing elements of the array is shown below.
output
Associative Arrays
44 vwww.starvlsi.com
Indices of Array
Syntax : [array names variablename] [Note: it displays the indices from bottom to top]
output
▪ You can use the indices of array to iterate through the associative array.
output
45 vwww.starvlsi.com
Strings
String Representations
▪ Unlike other languages, in Tcl, you need not include double quotes when it's only a single word. An example can
be
output
▪ When we want to represent multiple strings, we can use either double quotes or curly braces. It is shown below..
output
46 vwww.starvlsi.com
String Escape Sequence
▪ Horizantal Tab (\t) → It is used to shift the cursor to a couple of spaces to the right of same line
▪ New line (\n) → It is used to shift the cursor in the new line.
String commands
48 vwww.starvlsi.com
2. first Occurrence (syntax: string first string1 string2)
▪ Returns the index of first occurrence of string1 in string2. If not found, returns -1.
output
▪ Returns the index last occurrence of string1 in string2. If not found, returns -1.
49 vwww.starvlsi.com
5.String length (syntax: string length <string>)
Example: puts [string length “Hello world”] [Note: it considers the space is also one type of string I,e 5+1+5=11]
output
➢ Removes trimcharacters in left end of string. Here ,the content of string2 is removed in string1.
Example : puts [string trimright “Leadsoc technologies pvt Ltd” “pvt Ltd”
output
52 vwww.starvlsi.com
10.Trimleft string (syntax: string trimleft <string1> <string2>)
Example: puts [string trimleft “physical Design includes stages from floorplan to routing” “physical”]
53 vwww.starvlsi.com
12.Match pattern string (syntax: string match <string1> <string2>)
54 vwww.starvlsi.com
▪ In previous you have to observe that ,when appending the string with original string it displays the output with no
space in between them.
▪ If you want a space in between them then your using lappend directly or you have to given the space seperately
while appending.
output
14.Scan command:
▪ Scan command is used for parsing a string based on the format specifier.
55 vwww.starvlsi.com
▪ Here ‘m’ indicates to display the output with true or false I,e when the string matches the
given format it displays 1 otherwise it displays 0.
▪ If you didn’t mention ‘m’ it gives only string .it doesn’t parsing a string based on format
specifier.
Lists
Creating a List
56 vwww.starvlsi.com
output
output
57 vwww.starvlsi.com
Length of List
output
58 vwww.starvlsi.com
Insert Item at Index
Syntax: lreplace < list Name > <first Index > <last Index> < value1 value2 . . . . Valuen >
output
59 vwww.starvlsi.com
Set Item at Index
output
60 vwww.starvlsi.com
Sorting a list
Dictionary:
▪ Dictionary is an arrangement for mapping values to keys and it is same as like Arrays
Syntax: dict set dictname key value (here we can set single colour at a time)
or
dict create dictname key1 value1 key2 value2 . . . keyn valuen (here we can set muktiple colours at a
time)
61 vwww.starvlsi.com
Example
output
Size of Dict
Example output
62 vwww.starvlsi.com
Value for key in Dict
Example
output
63 vwww.starvlsi.com
All Values in Dict
64 vwww.starvlsi.com
Foreach Loop
▪ Whenever we have a collection of objects and we need to have iterations for all the objects then we can
use Foreach loop.
1.To print every value in a list together with the square and cube of the value
65 vwww.starvlsi.com
2. How to find the average of numbers in tcl.
ooutput
Note: Here, “gets stdin “ means it have taken the values from the user like scanf in C language.
66 vwww.starvlsi.com
Procedure
▪ Procedures are nothing but code blocks with series of commands that provide a specific reusable functionality.
▪ Let’s first define our procedures. we do that using the proc keyword.
67 vwww.starvlsi.com
Example
68 vwww.starvlsi.com
Example (cont..)
output
69 vwww.starvlsi.com
2.Example for finding average of numbers using proc
Output
70 vwww.starvlsi.com
File Handling
▪ Tcl supports file handling with the help of the built in commands open, read, puts, gets, and close.
1.Opening Files :
▪ Here, file name is the name of the file and accessmode can have any of the following rules.
Mode Description
r Opens an existing text file for reading purpose and the file must exist.
r+ Opens a text file for reading and writing both. File must exist already
w Opens a text file for writing, if it does not exist, then a new file is created
w+ Opens a text file for reading and writing both.If it does not exist, then a new file is created
a Opens a text file for writing in appending mode and file must 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
71 vwww.starvlsi.com
2.Closing a File :
▪ Any file that has been opened by a program must be closed when the program finishes using that file
3.Writing a File:
Fxample output
▪ When the above code is compiled and executed, it reads the file created in previous section and produces the result
73 vwww.starvlsi.com
5.Gets:
▪ gets will copy one line from the file and put in the variable .
output
74 vwww.starvlsi.com
6. End of file:
▪ use eof command to check the end of file position.it returns 1 if an end of file condition occurred
otherwise it returns 0.
▪ The following code will read and print out the contents of a file line by line.
75 vwww.starvlsi.com
Regular Expressions:
▪ A regular expression is a sequence of characters that contains a search pattern. It consists of multiple
rules as shown below.
Rule Description
x Exact match
[a – z] Any lowercase letter from a - z
. Matches any single character
^ Beginning string should match
$ Ending string should match
\^ Backlash sequence to match special character ^.Similarly you
can use for other characters.
Here, -nocase : it ignores the case I,e it displays the matched string whether it is lowercase and uppercase.
-all : it is used to display all the matched strings.
78 vwww.starvlsi.com
.
Example 2: wild card matching
Here, we are searching the word between p and n characters (p.*n) with ignore the case
79 vwww.starvlsi.com
.
Example 3: Group matching and status.
80 vwww.starvlsi.com
81 vwww.starvlsi.com