VTA Training Course
Topics:
➢Introduction
➢Variable declaration
➢Data type
➢Operator
➢Array
➢List
➢String
➢Decisions
➢Loops
➢Procedures
➢Regular expression
➢File Handling
Introduction
### puts is for printing in command line
puts “Hello World”;
puts “Hello World without semicolon”
output:
Hello World
Hello World without semicolon
### Semicolon ‘;’ is also significant if you want to put comment after the end of
statement.
puts “hello world” #comment
Above statement will throw syntex error
Puts “hello world”; # comment after semicolon
Above statement is correct.
Variable declaration
Input:
Set str “this is string”;
Set value 1.5;
puts “$str”;
puts “the value is $value”;
output:
this is string
this is value 1.5
Dollar ‘$’ is used as prefix with variable to print variable value in command line.
Square braces ‘[]’ are used for assigning value to variable from other expressions.
set a “5”;
set b $a; # this statement will assign b to a
Below statement will also assign b to a but in single statement
set b [set a “5”];
It will take statement inside square braces, evaluate it, and, assign output of it to
the variable b.
*** Curly Braces
Braces can also be used for printing in command line. Syntex is as follows:
puts “string in double quotes”
puts {string in curly braces}
output:
string in double quotes
string in curly braces
Why the curly brace ‘{‘ is required when double quote is already there for
printing?
Curly braces doesn’t recognize variable. It print all the $variables as it is.
set value 1.5;
puts {the value is $value};
put “the value is $value”
output:
the value is $value
the value is 1.5
*** Expr statement
Expr is used to evaluate the expression.
Syntex:
expr variable1 operator variable2
set a “5”;
set b “3”;
set c [expr “$a + $b”]; # ”[]” is used to put output of expr statement into variable
c.
puts “addition of a and b is $c”;
output:
addition of a and b is 8
Operators
Arithmetic Operators
Lets A = 5; B = 10
Operator Description Example
+ Adds two operands A + B will give 15
- Subtracts second operand from the first A - B will give -5
* Multiplies both operands A * B will give 50
/ Divides numerator by de-numerator B / A will give 2
% Modulus operator and remainder of after an integer A % B will give 5
division
Relational Operators
Let's A = 5; B = 10
Operator Description Example
== Checks equality of two operands. If equal condition (A == B) is not true
becomes true
!= Checks equality of two operands. If not equal (A != B) is true
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 the (A < B) is true
value of right operand, if yes then condition
becomes true.
>= Checks if the value of left operand is greater than or (A >= B) is not true
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
Let's A = 1; B = 0
Operator Description Example
&& 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
Let's A = 50; B = 30
Operator Example
& A&B = 01 0010
| A | B = 11 1110
^ A^B = 10 1100
<< A<<2 = 11 001000
>> A>>2 = 001100
Ternary Operator
Operator Description Example
?: If Condition is true? Then value X expr { (0 < 1) ? [puts 100] : [puts 50] }
: Otherwise value Y Result: 100
***Example
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"
Arrays
***Array Declaration: Array are ordered set of values
The syntax is:
set ArrayName (Index) value
example:
set institute (0) vlsi
set institute (1) training
set institute (2) academy
puts $institute (0)
puts $institute (1)
puts $institute (2)
Output:
Vlsi
Training
Academy
*** Size of Array
The syntex for calculating size array is shown below
[array size variablename]
example:
set institute (0) vlsi
set institute (1) training
set institute (2) academy
puts [array size institute]
output:
3
***Array Iteration
set institute (0) vlsi
set institute (1) training
set institute (2) academy
for { set index 0 } { $index < [array size institute] { incr index } {
puts "institute($index) : $institute($index)"
}
Output:
institute (0) : vlsi
institute (1) : training
institute (2) : academy
List
***Declaring a list
set color {red green blue yellow}
puts $color
output:
red green blue yellow
set color [list red green blue yellow]
puts $color
output:
red green blue yellow
***Append item to a list
set x green
append x “ ” “blue”
lappend x “red”
lappend x “yellow”
puts $x
output: green blue red yellow
***Length of list
set color {red green blue yellow}
puts [llength $color]
output:
4
***access index
set color {red green blue yellow}
puts [lindex $color 1]
output:
green
***insert at index
set color {red green blue yellow}
set color [linsert $x 3 black white
puts $color
output:
red green blue black white yellow
***replace items at indices ***set items at index ***sorting a list
set x {orange blue red green} set x {orange blue red green} set x {orange blue red green}
set x [lreplace $x 2 3 black white] lset x 0 black set x [lsort $var]
puts $x puts $x puts $x
Result: orange blue black white Result: black blue red green Result: blue green orange red
Strings
***example on string
set myVariable "hello world"
puts $myVariable
set myVariable {hello world}
puts $myVariable
output:
hello world
hello world
Escape sequence Meaning
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\n Newline
\t Horizontal tab
\v Vertical tab
***Example on uses of escape character ***example on string compare
string compare "abc" "xyz“
puts "Hello\tWorld\n\nNeural"; set s1 "Hello"
set s2 "HELLO“
output: puts [string compare $s1 $s2]
Hello World puts [string compare –nocase $s1 $s2]
Neural
output:
1
0
***example on string methods
set s1 "Hello World"
set s2 "o"
puts "First occurrence of $s2 in s1"
puts [string first $s2 $s1]
puts "Character at index 0 in s1"
puts [string index $s1 0]
puts "Last occurrence of $s2 in s1"
puts [string last $s2 $s1]
output:
First occurrence of o in s1
4
Character at index 0 in s1
H
Last occurrence of o in s1
7
***example on string match ***example on format command
set s1 "test@test.com" puts [format "%f" 43.5]
set s2 "*@*.com" puts [format "%e" 43.5]
puts "Matching pattern s2 in s1" puts [format "%d %s" 4 tuts]
puts [string match "*@*.com" $s1 ] puts [format "%s" “Tafuri Tech"]
puts "Matching pattern tcl in s1" puts [format "%s" “Tafuri\ Tech"]
puts [string match {tcl} $s1] puts [format "%x" 40]
output: output:
Matching pattern s2 in s1 43.500000
1 4.350000e+01
Matching pattern tcl in s1 4 tuts
0 “Tafuri
“Tafuri Tech"
28
*** example on scan command ***example on string is
puts [scan "90" {%[0-9]} m] set str {}
puts [scan "abc" {%[a-z]} m] puts [string is true -strict $str]
puts [scan "abc" {%[A-Z]} m] puts [string is false -strict $str]
puts [scan "ABC" {%[A-Z]} m] puts [string is integer -strict $str]
puts $m puts [string is alpha -strict $str]
output: output:
1 0
1 0
0 0
1 0
Task: Check what will happen if strict
option is not used.
Decisions
*** if statement
The syntax of an 'if...else' statement in Tcl language is –
if {boolean_expression} {
# statement(s) will execute if the boolean expression is true
} else {
# statement(s) will execute if the boolean expression is false
}
***if statement ***if-else statement
set a 10 set a 100
if { $a < 20 } { if {$a < 20 } {
puts "a is less than 20" puts "a is less than 20"
} } else {
puts "value of a is : $a" puts "a is not less than 20"
output: }
a is less than 20 puts "value of a is : $a“
value of a is : 10 output:
a is not less than 20
value of a is : 100
Loops
***for loop
The syntax of a for loop in Tcl language is –
for {initialization} {condition} {increment} {
statement(s);
}
***for loop
for { set a 10} {$a < 15} {incr a} {
puts "value of a: $a"
}
output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
***while loop
The syntax of a while loop in Tcl language is −
while {condition} {
statement(s)
}
***example on while loop
set a 10
while { $a < 15 } {
puts "value of a: $a"
incr a
}
output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
*** foreach loop
The syntax of ‘foreach” in tcl language-
foreach variable $list {
puts $variable
}
*** example on foreach loop
set numbers {1 2 3 4 5 6 7 8 9 10}
foreach x $numbers {
puts "x = $x"
}
Output:
x=1
x=2
x=3
x=4
x=5
x=6
x=7
x=8
x=9
x = 10
*** example on foreach loop
Set x {}
Foreach {i j} {a b c d e f } {
Lappend x $j $i
}
puts $x
Output:
badcfe
*** example on foreach loop
set x {}
foreach i {a b c} j {d e f g} {
lappend x $i $j
}
Procedures
Basic structure
proc procedureName {arguments} {
body
}
*** example procedures
proc helloWorld {} {
puts "Hello, World!"
}
helloWorld
***Proc with multiple arguments
proc add {a b} {
return [expr $a+$b]
}
puts [add 10 30]
output:
40
***Procedures with Default Arguments
proc add {a {b 100} } {
return [expr $a+$b]
}
puts [add 10 20 ]
puts [add 40]
output:
30
140
Regular expression
Operator Description
^ Matches the beginning of a string
$ Matches the end of a string
. Matches any single character
* Matches any count (0-n) of the previous character
+ Matches any count, but at least 1 of the previous character
[…] Matches any character of a set of characters
[^…] Matches any character *NOT* a member of the set of characters
following the ^
(…) Groups a set of characters into a subSpec.
***Find & Replace
regsub [options] exp string subSpec varName
Match regular expression exp against string string, making replacements defined
by subSpec, and store the result in variable varName.
example:
set mystring “A quick brown fox jumped over a brown lazy dog”
if {[regexp -nocase “brown” $mystring]} {
regsub -nocase -all “brown” $mystring “white” $mystring
puts $mystring
}
output: A quick white fox jumped over a white lazy dog
*** Wild card matching
***Example 1:
set res “A quick brown fox jumped over a brwn lazy dog”
foreach element $res {
if {[regexp {b.*n} $element]} {
puts $element
}
}
output:
brown
Brwn
***Example 2:
set full [regexp -all -inline {(br\S+)} $res]
output:
[find yourself]
*** Group matching and status
example:
set sample “Where there is a will, There is a way”
set result [regexp {[a-z]+} $sample match]
puts “match_status<$result> matched string:<$match>”
set result [regexp {([A-Za-z]+) ([a-z]+)} $sample match sub1 sub2]
puts “match_status<$result>Matched_string:<$match>
1st_string:<$sub1>2nd_string:<$sub2>”
output:
match_status<1>matched string:<here>
match_status<1>Matched_string:<Where there>
1st_string:<Where>2nd_string:<there>
***Direct replace and match count
Example:
set sample “Where there is a will, There is a way.”
regsub “way” $sample “abundance” sample2
puts “old_string:$sample \nNew_string: $sample2”
#Use the -all option to count the number of “words”
puts “Number of matching words: [regexp -all {[^ ]+} $sample]”
File Handling
***Open filename access mode
Mode Description
r Opens an existing text file for reading purpose and the file must exist. This is the
default mode used when no accessMode is specified.
w Opens a text file for writing, if it does not exist, then a new file is created else
existing file is truncated.
a Opens a text file for writing in appending mode and file must exist. Here, your
program will start appending content in the existing file content.
r+ Opens a text file for reading and writing both. File must exist already.
w+ Opens a text file for reading and writing both. It first truncate the file to zero
length if it exists otherwise create the file if it does not 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.
*** File Handling
***Example 1: Read and Write in a file
set fp [open "input.txt" w+]
puts $fp "test"
close $fp
set fp [open "input.txt" r]
set file_data [read $fp]
puts $file_data
close $fp
output: test
*** example 2: read and write in a file
set fRead [open infile.txt r]
set fWrite [open outfile.txt w]
while {![eof $fRead]} {
set line [gets $fRead]
set line [string toupper $line]
puts $fwrite $line
}
close $fRead
close $fWrite
Thank You