TCL
Tool Command Language
Contents (session-1)
• Introduction
• Syntax
• Basic commands
Introduction
• Tcl (“Tool Command Language”) pronounced like “tickle”) is a
scripting language created by John Ousterhout.
• Less syntax compared to other languages
• Most of the EDA tools support tcl
• String based
• everything can be done dynamically (no variable declaration)
• Use tclsh in unix shell to invoke tcl shell
Syntax
• Basic syntax : command arg1 arg2 arg3 ...
• commands are the basic execution elements.
• command is followed by arguments, each separated by white space or tabs.
• Each command can be separated by newline or semicolon(;)
• Supports command nesting , use ([ ])
• command [command arg1 arg2 ..] arg1 arg2 ..
• Substitution Execution
• Use # for comments
Basic commands
• set : to assign value to a variable
• set <first_argument> <second_argument>
• it places the second argument in the memory space referenced by the first
argument
• Ex: set a 5 #set the variable a to 5
• puts : to output a value of a variable, default is std output
• puts $a #The dollar sign tells Tcl to use the value of the variable
• unset : removes variable
• exec : to run unix commands
Sample code
• set a b
• set b 5
• puts a outputs a
• puts $a outputs b #value located @a
• puts $b outputs 5 #value located @b
• unset a
• puts $a errors out “can't read "a": no such variable”
• exec ls lists out files in current directory
Grouping
• Multiple words can be grouped by double quotes or curly braces { }
into one argument
• set mystring “I am going for PD training”
• puts $mystring I am going for PD training
• set mystring {I am going for PD training}
• puts $mystring I am going for PD training
• Key difference
• quotes allow substitutions to occur in the group, while curly braces prevent
substitutions.
Sample code
%set a 5
•5
%set mystr "value of a is $a"
• value of a is 5
% set mystr {value of a is $a}
• value of a is $a
• Note: difference in output of above two variable assignment
Math Expressions
• Tcl interpreter itself does not evaluate math expressions
• Tcl just does grouping, substitutions and command invocations
• % 1 + 2 invalid command name "1"
• %puts 1+2 1+2
• expr command is used to parse and evaluate math expressions
• Syntax: expr arg1 arg2 ….
• expr 1 + 2 3
• set a 1; set b 2; expr $a + $b 3
• Best practice to place arguments for expr in curly braces, as it does
substitution
• expr {$a + $b}
Math Expressions
• abs(x) - Absolute value (negate if negative)
• expr {abs(-3)} 3
• ceil(x) - return the next larger integer number
• expr {ceil(1.2)} 2.0
• floor(x) - return the next smaller integer number
• expr {floor(1.2)} 1.0
• double(x) – converts integer to floating number
• expr {double(5)} 5.0
Math Expressions
• int(x) : converts float value to integer
• expr {int(5.9)} 5
• min(arg1,arg2..) returns minimum value of input arguments
• expr {min(3,10,1)} 1
• max(arg1,arg2..) returns maximum value of input arguments
• expr {max(3,10,1)} 10
• pow(x,y) power function x to the power of y
• expr {pow(2,4)} 16.0
Command nesting
• In Tcl, multiple commands can be nested using [ ]
• set a 5
• set b 6
• set c [expr {$a + $b}]
• puts $c 11
Assignment
• Try variable assignments using curly braces and double quotes
• a=100, b=10, c =50.
• Program to output “Minimum value of a, b & c is : <value>”
• Program to output “Maximum value of a, b & c is : <value>”
• Program to assign d with sum of a, b & c. print d value
• Get nearest lower & upper values of 999.999
Contents (session2)
• Variable types
• Lists
• Arrays
Lists
• List is one of the basic data-type available in Tcl
• List is used for representing an ordered collection of items
• set ListName {item1 item2 item3 … itemn}
• set ListName [list item1 item2 item3 … itemn]
• set ListName [split “items separated by character” character]
• List can include different types of items in the same list
• Further, a list can contain another list
Lists
• set var1 [list and xor nor]
• set var1 {and xor nor}
• set var1 “and xor nor”
• set var1 [split “and_xor_nor” _]
• All above four commands sets var1 and xor nor
• set var2 [list and 2 xor 3 nor 4]
• set var3 [list xor [list nand buff inv] [list cell1 cell2]]
List operations
• llength $list_name : outputs length of list
• llength $var1 3
• lindex $list_name index: selecting list item at specific index
• lindex $var1 0 and
• lappend list_name value : to append values to existing list (will
modify list)
• lappend var1 buff and xor nor buff
• linsert $list_name index value1 value2 .. valuen : to insert list items at
particular index (will not modify list)
• linsert $var1 3 inv1 inv2 and xor nor inv1 inv2 buff
List operations
• lreplace $listname first_index last_index value1 value2 ..valuen
• To replace the values in given range of indices (will not modify list)
• set var1 [list and or nand inv1 inv2 inv3 buff]
• set var3 [lreplace $var1 3 5 INV1 INV2 INV3]
• puts $var3 and or nand INV1 INV2 INV3 buff
• set var4 [lreplace $var1 3 3 INV1] and or nand INV1 inv2 inv3 buff
• lset list_name index value : to replace value at given index
• It modifies existing list
• lset var1 1 xor
• puts $var1 and xor nand inv1 inv2 inv3 buff
List operations
• lassign $list_name var1 var2 ..varn : to transform list values to
variables
• lassign $var1 pd1 pd2 pd3 puts $pd1 -> and
• lsort $list_name : to sort list values
• -increasing # ascending order
• -decreasing #descending order
• -unique #uniqified list values
• lsearch $list_name search_pattern: to search for list values, by default
returns index matching pattern if matching pattern exists
• Returns -1 if no matching found
List operations
• set var3 [list and or nand INV1 inv2 inv3 buff]
• lsearch $var3 inv2 4 #index of value inv2
• lsearch –inline $var3 inv2 inv2 #value matching pattern
• lsearch $var3 inv* 4 #only first matched pattern is returned
• lsearch -all $var3 inv* 4 5 #all indices of matched pattern
Few more commands
• info exists var_name : returns 1 if variable var_name exists, else 0
• info functions pattern: returns expr related functions that matches
pattern
• info functions ce* ceil
• incr var_name value : to increment var_name by certain value
• set b 1
• incr b 2
• incr b 5 7
Arrays
• A Tcl array is a container of variables.
• represented as array_name(key)
• array option arrayName ?arg arg ...?
• Syntax for conventional array
• set ArrayName(key) arg1 arg2..
• set gatecount(1) 100
• set gatecount(2) 800
• array size ArrayName
• array size gatecount 2
Associative Arrays
• Arrays in most languages can only be indexed by integers, but in tcl the
name of a key variable in an array may be any string
• array set gatecount {
nand 10
nor 30
buff 50}
• puts $gatecount(nand) 10
• array get ArrayName pattern :Returns a list containing the names of all of
the elements in the array that match pattern
• array get gatecount nor nor 30
• array names : Gets the names of all keys
• array names gatecount nand nor buff
Arrays
• array unset ArrayName ?pattern? : Unsets all of the elements in the array that
match pattern
• array unset gatecount nor
• array names gatecount nand buff
• array exists ArrayName: Returns 1 if arrayName is an array variable, 0 if there is
no variable by that name or if it is a scalar variable
• array exists gatecount 1
If else conditions
• Syntax: if {condition1} {
statement
} elseif {condition2} {
statement
} else {
statement
}
Loops
• for {set x 0} {$x<10} {incr x} {
puts "x is $x"
}
• foreach : to iterate over list, multiple lists can be used
• foreach varname list body
foreach varlist1 list1 ?varlist2 list2 ...? body
Loops
• while {condition} {
statement1
statement2
}
Eg: set i 0
while {$i < 5} {
puts $i
incr i
}
Switch
• switch $varName {
pattern1 { statement}
pattern2 {statement}
patternN {statement}
default {statement}
}
which ever pattern $varName match those statements get executed
Switch
• set a 20
• set b 30
• set arth_ops {sum diff product div}
• foreach op $arth_ops {
switch $op {
sum { set c [expr {$a + $b}]; puts "sum: $c"}
diff { set c [expr {$a - $b}]; puts "diff: $c"}
product { set c [expr {$a * $b}]; puts "product: $c"}
default {puts "operations $op doesn't exist"}
}
}
Procedures
• To provide specific reusable functionality
• Used to avoid same code being repeated in multiple locations
• Procedures are equivalent to the functions used in many programming
languages
• Syntax: proc procedureName {arguments} {
body
}
• Procedure can also be created without arguments
• return is used return the values from current procedure to next levels
Procedures
• Proc with no arguments
• proc dollar_price { } {
return 72;
}
• set c [dollar_price]; puts $c 72
• Proc with multiple arguments
• proc add {a b} {
return [expr {$a+$b}]
}
set c [add 10 30]; puts $c 40
Procedures
• Proc with variable arguments ( you can pass on list as argument)
• 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}] 65
puts [avg {70 80 50 }] 66
Procedures
• Proc with default arguments:
• Default arguments are used to provide default values that can be used if no
value is provided
• proc add {a {b 100}} {
return [expr {$a+$b}]
}
puts [add 10 30] 40
puts [add 10] 110
Procedures
• Recursive Procedures : procedure within same procedure
• proc factorial {number} {
if {$number <= 1} {
return 1
}
return [expr $number * [factorial [expr $number - 1]]]
}
puts [factorial 3] 6
puts [factorial 5] 120
Misc
• Use man <command_name> in tclshell to get manual page of any
command
• man proc
• Use \ to escape special characters
• set a \$b; puts $a $b
• Command to continue in next line (new line gets skipped)
• set lst1 [list a b c \
d e f]
• Use source <file_name>.tcl to source your tcl files
Assignment
• Create a proc named capital_city which prints capital city if provided
state name
• Eg: capital_city telangana Capital of Telangana is Hyderabad
• Hint: use switch statement inside proc
• Proc table_of to print table for a given number
• table_of 7 7 x 1=7 … 7 x 10 = 70
• Proc max_of to find maximum value in list
Scope of variables
• Each procedure has a local scope of variable
• Variables introduced in procedure only live for the duration of the procedure call
• After procedure returns, those variables are undefined
• Variables defined outside procedure are not visible to a prcocedure
Eg:
• proc test1 { } {
set a 10
}
• set a 20; #a is having value 20
• test1;
• puts $a ? # output will be 20
Scope of variables
• Variables defined out of procedure can be made visible by procedure using
below scope commands
• global
• upvar
• Top level scope is called global scope
• global var_name1 var_name2 …
• proc test1 { } {
global a
set a 10
}
• set a 20; #a is having value 20
• test1;
• puts $a ? # output will be 10
Scope of variables
• Call by name
• upvar associates a local variable to up in call stack
• upvar ?level? varName localVar
• Level argument is optional (default 1)
• Incr command is best example for upvar
• proc incr2 {a} {
upvar $a b
set b [expr {$b + 2}]
return $b
}
Handling Strings
• Tcl also supports various string operations
• Syntax:
• string operation stringvalue otherargs
• string compare $string1 $string2
• Returns 0 if both are equal
• Returns -1 if $string1 sorts before $string2
• Returns 1 if $string2 sorts before $string1
Eg: string compare bombay bombay 0
string compare bombay delhi -1
string compare delhi bombay 1
Handling Strings
• string first $str1 $str2
• Returns index of first occurrence of str1 in str2 if match is found
• Returns -1 if no match is found
• Eg: string first m bombay 2
string first d bombay -1
string first am "I am an engineer"
• string last $str1 $str2
• Returns index of last occurrence of str1 in str2 if match is found
• Returns -1 if no match is found
• Eg: string first b bombay 0
string last b bombay 3
Handling Strings
• string index $str1 index_value
• Returns the character at specified index
• Eg: string index hyderabad 4 r
• string length $str
• Returns the no. of charatcters in string
• Eg: string length hyderabad 9
• string match pattern $str
• Returns 1 if str matches pattern, else 0
• Eg: string match hyd* hyderabad 1
Handling Strings
• string range $str i j
• Returns the range of characters in str1 from i to j
• Eg: string range “I am going for pd training” 3 8 m goin
• string tolower $str
• Return str in lower case
• string toupper $str
• Return str in upper case
• string trim $str ?chars?
• Trim the characters chars from both ends of string
• Eg: string trim hyderabad bad hydera
string trim "bad in hyderabad" bad in hydera
string trim hyderabad ra hyderabad
Handling Strings
• string trimleft $str ?chars?
• Trim the characters chars from beginning of string
• Eg: string trimleft hyderabad bad hyderabad
string trimleft "bad in hyderabad" bad in Hyderabad
• string trimright $str ?chars?
• Trim the characters chars from end of string
• Eg: string trimright hyderabad bad hydera
string trimright "bad in hyderabad" bad bad in hydera
File handling
• Tcl can also open, read & write to files
• open command is used for file handling
• Syntax:
• open file_name ?access? ?permissions?
• access can take below values
• r – open for reading, file must exist
• r+ - open for reading and writing, file must exist
• w – open for writing, truncate if exists, creates if it does not exist
• w+ - open for reading and writing, truncate and create
• a –open for writing, file must exist, data is appended to file
• a –open for reading and writing, file must exist, data is appended to file
File handling
• Writing to a file
• set fileID [open <file_name> w]
• puts $fileID “This is my sample script for tcl file handling”
• close $fileID
• Reading a file
• set fileID [open <file_name> r]
• gets is used to read a line from file
• Syntax: gets $fileID <var_name> # reads a line from file and stores in
var_name
• Use while loop to read line by line
• while {[gets $fileID line] != -1} { statements } close $fileID
• while {[gets $fileID line] >= 1} {statements } close $fileID
File handling
• Reading a file
• set fileID [open <file_name> r]
• set var_name [read $fileID] read complete file and stores in var_name
• close $in
• set lines [split $var_name "\n"] splitting var_name by newline
• foreach line $lines { statements }
• Append lines to existing file
• set fileID [open <file_name> a]
File system
• file exists <file_name>
• Check if file_name file exists , returns 1 if file exists ,elese 0
• file tail <path for file>
• Returns all characers after last “/”
• file tail /a/b/c.txt c.txt
• file extension <file_name.
• Returns all character after “.”
• File extension /a/b/c.txt txt
Regular expressions
• regexp is used to handle regular expressions
• Syntax
regexp ?options? pattern string ?var1 sub1 sub2 … subn?
• If string matches pattern, then result of match is stored in var1
• The remaining variables (sub1 .. subn) are substrings of string that matched
corresponding sub pattern in pattern
• set str1 "This is my PD training“
• regexp {[A-Z][A-Z]} $str1 match
• puts $match PD
Regular expressions
• * symbol matches zero or more occurrences of the character immediately
preceding the *
• a* will match a, aa, abc or blank string
• regexp h* hyderabad 1
• regexp z* hyderabad 1
• + symbol behaves same as the *, except that it requires at least one
character to match
• a+ will match a, aa, abc but not blank string
• regexp z+ hyderabad 0
• . matches any single character (m.d matches mad)
• ? symbol matches zero or one occurrences of the character immediately
preceding the ?
Regular expressions
• regexp {^[A-Z][a-zA-Z]*} $str1 match
• puts $match This
• regexp {(^[A-Z][a-z]+) ([a-z]+)} $str1 match a b
• puts $match This is
• puts $a This
• puts $b is
• regexp {(^[A-Z][a-z]+) .* ([A-Z][A-Z])} $str1 a b c
• puts $a This is my PD
• puts $b This
• puts $c PD
Regular expressions
• regsub is used to do string substitution based on pattern matching
• Syntax: regsub ?options? pattern string subspec ?varName?
• regsub {[A-Z][A-Z]} $str1 TCL newstring
• puts $newstring This is my TCL training
• regsub {[A-Z][A-Z]} $str1 TCL This is my TCL training
• regsub top top_ports bot
• set str1 “top top_all top_down”
• regsub top $str1 bot bot top_all top_down
• regsub -all top $str1 bot bot bot_all bot_down