You are on page 1of 81

Topic

Tcl Scripting
Introduction:

▪ Tcl is shortened form of Tool Command Language

▪ John Ousterhout of the University of California, Berkeley, designed it.

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

▪ 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

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

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

▪ Scalable websites that are often backed by databases.

▪ High performance web servers build with TclHttpd.

▪ Tcl with CGI based websites.

▪ 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.

▪ A simple example to set a value to a variable and print it is shown below.

set a 3 [here the value 3 is stored in variable a ]

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 .

▪ A simple example to add numbers is shown below.

puts [expr 1 + 6 + 9] output : 16 [Note: Expr is used for evaluating the mathematical Expressions]

3. Backslash Substitution :

▪ These are commonly called as Escape Sequences.

Escape Sequence Meaning


Single quote ( \‘ ) ‘ character
Double quote ( \ “ ) “ character
New line ( \n ) used to shift the cursor in new line
Horizantal tab (\t ) used to leave some space in b/w words

6 vwww.starvlsi.com
Example output

Mathematical Expressions :

▪ 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.

▪ you can change the precision by using tcl_precision special variable.

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

Operator Description Example

Addition (+) It adds the two Operands A+B will give 30

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

▪ Assume variable A holds 1 and variable B holds 0

Operatos Description Example

Logical AND (&&) If both the operands are non-zero, (A&&B) is false
then condition becomes true.

Logical OR ( || ) If any of the two operands is non- (A || B) is true


zero, then condition becomes
true.

Logical NOT ( ! ) Use to reverses the logical state !(A&&B) is true


of its operand.

15 vwww.starvlsi.com
Example

outoutput

16 vwww.starvlsi.com
Bitwise Operators

▪ Bitwise operator works on bits and perform bit-by-bit operation

▪ 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

A = 0000 1111 A =0000 1111 A = 0000 1111 A = 0000 1111


B = 0000 1101 B =0000 1101 B = 0000 1101 A << 2= 0011 1100
--------------------- -------------------- --------------------- A >> 2= 0000 0011
A&B = 0000 1101 A|B=0000 1111 A^B= 0000 0010

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 OR ( | ) It copies a bit if it exists in (A | B) will give 15, which is


either operand. 0000 1111

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

Operator Description Example


?: Ternary If Condition is true? Then value X : Otherwise value Y.

Example
output

20 vwww.starvlsi.com
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.

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

Syntax: Flow Diagram

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.

Syntax: while {condition} {


#statements
33 vwww.starvlsi.com
}
Flow Diagram EEExample

output

34 vwww.starvlsi.com
2. For Loop

▪ It executes a sequence of statements in multiple times until the condition is satisfied.

Syntax:

for {initialization} {condition} {increment} {

#statements;
}

Here is the flow to control in for loop.

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

for {initialization} {condition} {increment} { while {condition} {


for {initialization} {condition} {increment} { while {condition} {
#statements; #st atements;
} }
#statements; #st atements;
} }

▪ 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;

Flow Diagram Example

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

Here, when we are using continue inside of if loop


it will skip the iteration of the if statement(I,e it will skip 12)
and continue the next Statements after if statement
till the while Condition is satisfied (I,e it will continue 13,14)

41 vwww.starvlsi.com
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.

Syntax:
while {1} {
puts “This loop will run forever.”
}

▪ 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.

vwww.starvlsi.com
42
Arrays
▪ An array is a systematic arrangement of a group of elements using indices.

Syntax : set ArrayName (Index) value

▪ An example for creating simple array is shown below.


output

Size of Array

▪ It is used for calculating the array size.

Syntax: [array size variablename]


▪ An example for printing the size as shown below.
output

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

▪ Associative arrays have an index that is not necessarily a number.


output

44 vwww.starvlsi.com
Indices of Array

Syntax : [array names variablename] [Note: it displays the indices from bottom to top]
output

Iteration of Associative Array

▪ 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

1.String compare: It compares two strings.

Syntax: string compare string1 string2


It returns
0: if both strings are same.
1: if string1 comes after string2
-1: if string1 comes before string2
47 vwww.starvlsi.com
output

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

3. Index case (syntax: string index <string> <index value> )

▪ It returns the character at index in the string.


output

4. last occurrence (syntax: string last string1 string2)

▪ 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>)

▪ It returns the length of the 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

6.String range (string range <string> <index1> <index2>)

▪ It returns the range of characters from index1 to index2.

Example:50puts [string range “I am studying Tcl scripting” 2 10 ]


vwww.starvlsi.com
output

7.String tolower (syntax : string tolower <string> )

▪ It returns the complete string in lowercase.

Example: puts [string tolower “VlsI DesiGn” ]


output

8.String toupper (syntax: string toupper <string> )

▪ It returns the complete string in Uppercase.

Example: puts [string toupper “VlsI DesiGn”]


51 vwww.starvlsi.com
output

9.Trimright string (syntax: string trimright <string1> <string2>)

➢ 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>)

▪ It removes trimcharacters in left beginning of string.

Example: puts [string trimleft “physical Design includes stages from floorplan to routing” “physical”]

11.Trim string (syntax: string trim <string1> <string2>)

▪ It removes trimcharacters in both ends of the string .

Example: puts [string trim “::::vlsi design::::” “:” ]


output

53 vwww.starvlsi.com
12.Match pattern string (syntax: string match <string1> <string2>)

▪ It returns 1 if the string matches the pattern else returns 0

Example: puts [string match “*g*.com” test-id@goldenVLSI.com]

13.Appending string (syntax: append <original string > <appending string>)

▪ It appends string to original string itself .

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

▪ It is used for representing an ordered collection of items.

▪ It can include different types of items in the same list.

Creating a 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]

56 vwww.starvlsi.com
output

Appending Item to a List

Syntax: append listName split_character value


or
lappend listName value

output

57 vwww.starvlsi.com
Length of List

Syntax: llength <list name>

▪ The below is an example of length of the list.

output

List Item at Index

Syntax: lindex <list name> <Index value>

▪ The below is an example


output Here , index_0 → orange
index_1 → blue
index_2 → red
index_3 → green

58 vwww.starvlsi.com
Insert Item at Index

Syntax: linsert <listName> <index_value> <value1 value2 value3….valuen>

▪ Example for inserting list item at specific index is given below.


output

Replace Items at Indices

Syntax: lreplace < list Name > <first Index > <last Index> < value1 value2 . . . . Valuen >

▪ Example for replacing list items at specific indices is given below

output

59 vwww.starvlsi.com
Set Item at Index

Syntax: lset <listName> <index_value> <value>

▪ Example for setting list item at specific index is given below

output

Transform List to Variables

Syntax: lassign <listName> < variable1 variable2 . . . Variablen>

▪ Example for transforming list into variables is given below.


output

60 vwww.starvlsi.com
Sorting a list

Syntax: lsort <listname>

▪ An example for sorting a list is given below..


output

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

Syntax : [ dict size dictname]

Example output

62 vwww.starvlsi.com
Value for key in Dict

Syntax : [dict get dictName keyName]

Example
output

All Keys in Dict

Syntax : [ dict keys dictname ] output

63 vwww.starvlsi.com
All Values in Dict

Syntax : [dict values dictname]


ooutput

Key Exists In Dict

Syntax: [dict exists dictname keyname ]


output

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.

syntax : foreach <object_name> < collection_of_objects> {


body
}
Examples:

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.

▪ It is used to avoid same code being repeated in multiple locations.

Syntax: proc procedureName {arguments} {


body
}
Steps:

▪ Let’s first define our procedures. we do that using the proc keyword.

▪ Nest step is to read the arguments using gets.

▪ The final step is to print all the required values

Syntax to call procedure : [procedurename $argument1 $argument2 . . . .]

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 :

▪ Tcl uses the open command to open files.

Syntax : open filename AccessMode

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

▪ To close a file, use the close command.

▪ Syntax: close filename

▪ Any file that has been opened by a program must be closed when the program finishes using that file

3.Writing a File:

▪ Puts command is used to write to an open file.

Syntax: puts $filename “text to write”

Example: set fp [open “input.txt” w+] output : text


puts $fp “text”
close $fp
▪ 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).
72 vwww.starvlsi.com
4.Reading a File :

▪ A simple command to read from the file.

set file_data [read $fp]

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:

Syntax: gets filename variableName

▪ gets will copy one line from the file and put in the variable .

▪ Example for reading file till end of file line by line

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.

set f [open somefile.txt r] set fp [open somefile.txt r]


While {1} { set line [gets $fp]
set line [gets $f] while {![eof $fp]} {
if {[eof $f]} { OR #process line
close $f puts “Read line :$line”
break }
}
Puts ”Read line : $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.

() Add the above sequences inside parenthesis to make a regular


expression.
76 vwww.starvlsi.com
.
Rule Description
* Matches any count (0-n) of the previous character
+ Matches any count,but atleast 1 of the previous character.

[a – z]? Should match 0 or 1 occurrence of the preceding x

{digit} Matches exactly digit occurrences of previous regex expression.


Digit that contains 0-9.

{digit ,] Matches 3 or more digit occurrences of previous regex


expression. Digit that contains 0-9.

{digit1,digit2] Occurrences matches the range between digit1 and digit2


occurrences of previous regex expression.

RegEx : it used for pattern match only.

Regsub : it used for both pattern match and substitution.


77 vwww.starvlsi.com
.
Example 1: How to find the word and replace that word using RegEx

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

You might also like