0% found this document useful (0 votes)
102 views

TCL Script

TCL is a scripting language that can be embedded into applications to provide programmability and extend functionality. It aims to allow programs to interact with each other. Key features include reduced development time, powerful user interface capabilities, platform independence, and powerful networking functions. TCL can be used for web applications, servers, desktop apps, and embedded applications. It provides variables, operators, conditional statements like if/else, loops like while and for, and procedures to structure programs.

Uploaded by

yamini
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views

TCL Script

TCL is a scripting language that can be embedded into applications to provide programmability and extend functionality. It aims to allow programs to interact with each other. Key features include reduced development time, powerful user interface capabilities, platform independence, and powerful networking functions. TCL can be used for web applications, servers, desktop apps, and embedded applications. It provides variables, operators, conditional statements like if/else, loops like while and for, and procedures to structure programs.

Uploaded by

yamini
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 48

TCL Scripting

What is TCL and its features?


• TCL stands for Tool Command Language.
• It is a combination of a scripting language and its own interpreter that gets embedded to the application, which we
develop with it.
• It aims at providing the ability for programs to interact with other programs and also for acting as an embeddable
interpreter.

Features

• Reduced development time.


• Powerful and simple user interface kit with integration of TK.
• Write once, run anywhere.
• possible to include TCL in C, C++, or Java to TCL or vice versa.
• Have a powerful set of networking functions.
Applications
• Scalable websites that are often backed by databases
• High performance web servers build with TCL Httpd
• TCL with CGI based websites
• Desktop GUI applications
• Embedded applications

tcl_version- Returns the current version of the TCL interpreter


Simple program to print a string:
#!/usr/bin/tclsh
puts "Hello World!"

Run the script


$ tclsh test.tcl

output:
Hello, World!

Comment:
#!/usr/bin/tclsh
# my first program in TCL
puts "Hello World!"
Variable Substitution

$ is used before the variable name and this returns the contents of the variable.
Ex: #!/usr/bin/tclsh
set a 3
puts $a ……………….result: 3

Backslash Substitution

These are commonly called escape sequences; with each backslash, followed by a letter having its
own meaning.
Ex: #!/usr/bin/tclsh
puts "Hello/nWorld“ ……………….result: Hello

World
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
Arithmetic Operators
The arithmetic operators perform addition (+), subtraction (-), multiplication (*), division (/),
and modulus(%) operations

Ex:- set a 20
set b 10
puts [expr $a + $b] ……………Result: 30
puts [expr $a - $b] ……………Result: 10
puts [expr $a * $b] ……………Result: 200
puts [expr $a / $b] ……………Result: 2
puts [expr $a % $b] ……………Result: 0
Relational Operators
Used to check the relational between two operands. If the condition is true
then the value returned is 1 else false return 0

ex: set a 20
set b 10
puts [expr $a > $b] ………………….Result: 1
puts [expr $a < $b] ………………….Result: 0
puts [expr $a >= $b]
………………….Result: 1
puts [expr $a <= $b] ………………….Result: 0
puts [expr $a != $b]
………………….Result: 1
puts [expr $a == $b] ………………….Result: 0
Logical Operators
• && If both the operands are non-zero, then condition becomes true and return 1 else return 0
ex: set a 20
set b 10
puts [expr $a && $b] …………………….Result: 1
• || If any of the two operands is non-zero, then condition becomes true and return 1 else return
0
ex: set a 0
set b 10
puts [expr $a || $b] …………………….Result: 1
• ! Used to reverse the result of any expression(only for single bit)
ex: set a 0
set b 1
puts [expr !$a] ] …………………….Result: 1
puts [expr !$b] ] …………………….Result: 0
Bitwise Operator
Bitwise operator works on bits and perform bit-by-bit operation.
• & (bitwise and)
• | (bitwise or)
• ^ (bitwise exclusive or)
• ~ (bitwise negation)
Ex:- set a10 #10 in bin-
00001010
set b 20 # 20 in bin-
00010100
puts [expr $a & $b] ……………Result: 0 0 0 0 0 0 0 0
puts [expr $a | $b] ........………Result: 0 0 0 1 1 1 1 0
puts [expr $a ^ $b] .…………….Result: 0 0 0 1 1 1 1 0
set c 7
puts [expr ~$c] ….………….Result: -8
Ternary Operator ( ?:)
Syntax : condition-expression ? expression_1 : expression_2

ex: set A 7
set result [expr $A > 6 ? true : false]
puts $result …………………….. result : true
Decisions
• Decision making structures require that
the programmer specifies one or more
conditions to be evaluated or tested by
the program

• Following is the general form of a


typical decision making structure found
in most of the programming languages:
TCL language provides following types of decision making statements:

• if statement

• if...else statement

• nested if statements

• switch statement

• nested switch statements


IF statement
• An if statement consists of a Boolean expression followed by one or more statements.

Syntax:
if {boolean_expression/condition} {
# statement(s) will execute if the Boolean expression is true
}

Ex:- set age 5


if {$age < 10} {
puts "Age is less than 10"
}
Output: Age is less than 10
IF…..ELSE Statement
• An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
Syntax:
if {boolean_expression/condition} {
# statement(s) will execute if the boolean expression is true
} else {
# statement(s) will execute if the boolean expression is false
}
Ex: set age 5
if {$age < 10} {
puts "Age is less than 10"
} else {
Puts "Age is greater than 10"
} ………….output: Age is less than 10
If...else if Statement
example:
• An ‘if’ statement can be followed by an optional else if...else set a 100
statement, which is very useful to test various conditions using if { $a == 10 } {
single if...else if statement. puts "Value of a is 10"
} elseif { $a == 20 } {
Syntax:
puts "Value of a is 20"
if {boolean_expression 1} { } elseif { $a == 30 } {
puts "Value of a is 30"
# Executes when the boolean expression 1 is true } else {
} elseif {boolean_expression 2} { puts "None of the values is matching"
}
# Executes when the boolean expression 2 is true puts "Exact value of a is: $a“
} else {
result:
# executes when the none of the above condition is true None of the values is matching
Exact value of a is: 100
}
Nested If Statement
• to nest if-else statements, which means you can use
one if or else if statement inside another if or else if
statement(s).

Ex: set a 10
Syntax: set b 20
if {$a == 10} {
If {expression_1} {
if {$b == 20} {
Body_1 puts "value of a is 10 and b is 20"
If {expression_2} { }
}
Body_2 result: value of a is 10 and b is 20
}
}
Switch Statement Nested switch
Nested switch statement means switch
This enables a variable to be tested for equality against statement inside a switch statement.
a list of values. It evaluates the list and returns the
result of that evaluation. If no values matches then Example:
default values will be returned. set a 100
set b 200
syntax:
switch switchingString { switch $a {
100 {
matchString1 { puts "The value of a is $a"
body1 switch $b {
} 200 {
puts "The value of b is $b"
matchString2 { }
body2 }
} }
}
... result:-
matchStringn { The value of a is 100
bodyn The value of b is 200
}
Loops
• A loop statement allows us to execute a statement or group of
statements multiple times

types of loops
• while loop
• for loop
• foreach loop
• nested loop

loop control statements


• break
• continue
While Loop
A while loop statement in TCL language repeatedly executes a target
statement as long as a given condition is true.

Syntax:
while {condition} {
statement(s)
}
Ex: set a 10 result:
value of a: 10
while { $a < =15 } { value of a: 11
puts "value of a: $a" value of a: 12
value of a: 13
incr a value of a: 14
value of a: 15
}
For Loop
A for loop is a repetition control structure that allows you to efficiently write a code that
needs to be executed for a specific number of times.

Syntax:
for {initialization} {condition} {increment} {
statement(s);
}
result:
Ex: value of a: 10
for loop execution value of a: 11
value of a: 12
for { set a 10} {$a < 15} {incr a} { value of a: 13
puts "value of a: $a" value of a: 14
}
Foreach Loop
The foreach command implements a loop where the loop variable(s) take on values from one
or more lists.

syntax:
foreach <object name> <collection of objects> {
body
}

Ex: result:
15aw
foreach a [list 1 2 3 4] b [list 5 6 7 8] c [list a b c d] d [list w x y z] { 26bx
puts "$a $b $c $d" 37cy
48dz
}
Nested Loops
TCL allows to use one loop inside another loop.
Ex: Find the prime numbers from 2 to 50:

Syntax: set j 0;
for {set i 2} {$i<100} {incr i} {
for {initialization} {condition} {increment} { for {set j 2} {$j <= [expr $i/$j] } {incr j} {
for {initialization} {condition} {increment} {
if { [expr $i % $j] == 0 } {
statement(s); break
}
} }
statement(s); if {$j >[expr $i / $j] } {
puts "$i "
} }
}
result: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
Loop Control Statements
Loop control statements change execution from its normal sequence.

Break Statement:
The break statement in TCL language is used for terminating a loop.
Syntax:
break;
Ex: set a 10
while {$a < 20 } { result:
value of a: 10
puts "value of a: $a" value of a: 11
incr a value of a: 12
value of a: 13
if { $a > 15} {
value of a: 14
break # terminate the loop using break value of a: 15
statement
}
Continue Statement:
• 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;

Ex: set a 10
while { $a < 15 } {
result:
if { $a == 12} { value of a: 10
incr a value of a: 11
value of a: 12
continue #skip the iteration value of a: 13
} value of a: 14

puts "value of a: $a"


incr a
}
Arrays
An array is a systematic arrangement of a group of elements using indices.
syntax: set ArrayName(Index) value
Ex: set languages(0) TCL result:
set languages(1) "C Language" TCL
puts $languages(0) C Language
puts $languages(1)

Size of Array
syntax: [array size variablename]
Ex: set languages(0) TCL result:
set languages(1) "C Language" 2
puts [array size languages]
Strings
A string is a sequence of characters. Strings can contain alphanumeric character, just numbers,
Boolean, or even binary data.
Ex: set myVariable "hello world"
result: hello world
puts $myVariable

string index
Returns the character at index
Ex: set s1 "Hello World"
set s2 "o"
puts "Character at index 0 in s1“
result: Character at index 0 in s1 H
puts [string index $s1 0]
Length of String:
Returns a decimal string giving the number of characters in string
Ex: set s1 "Hello World"
puts "Length of string s1" result:
puts [string length $s1] Length of string s1 11

string match
Returns 1 if the string matches the pattern.
Ex: set s1 "test1.test.com"
set s2 ".com"
puts "Matching pattern s2 in s1"
result:
puts [string match ".com" $s1 ] Matching pattern s2 in s1 1
String Comparison:
Perform a character-by-character comparison of strings string1 and string2 if equal value returned is 0
else 1
Ex: puts [string compare 12 12] Result: 0

Append Command
Used to append at the end of the existing string
Syntax: append string string
Ex: set s1 "Hello"
append s1 " World"
puts $s1 Result: Hello World
String Commands
• string range: Returns a range of consecutive characters from string

• string tolower: Returns a value equal to string except that all upper case letters have been converted to
lower case

• string toupper: Returns a value equal to string except that all lower case letters have been converted
to upper case.

• string wordend: Returns the index of the character just after the last one in the word containing
character index of string

• string wordstart: Returns the index of the first character in the word containing character index of
string.

• string last: last string1 string2 : Returns the index last occurrence of string1 in string2. If not found,
returns -1.
Lists
• List is one of the basic data-type available in TCL.
• It is used for representing an ordered collection of items.

Creating a List
Syntax:
set listName { item1 item2 item3 .. itemn }
# or set listName [list item1 item2 item3]

Ex: set colorList1 {red green blue}


set colorList2 [list red green blue]
result: red green blue
red green blue
Appending Item to a List
syntax: lappend listName value

Ex: set var orange


lappend var "red"
lappend var "green"
puts “$var” result: orange red green

lassign: copying values to variables/Transform List to Variables

Ex: set var {orange blue red green}


lassign $var colour1 colour2
puts $colour1 $colour2 result: orange blue
Length of List:
syntax: llength listName
Ex: set var {orange blue red green}
puts [llength $var] result: 4

LIndex: selecting list item at specific index


syntax: lindex listname index
Ex: set var {orange blue red green}
puts [lindex $var 1] result: blue

linsert: inserting list items at specific index


syntax: linsert listname index value1 value2..valuen
Ex: set var {orange blue red green}
set var [linsert $var 3 black white]
puts $var result: orange blue red black white green
lreplace: replacing list items at specific indices
syntax: lreplace listname firstindex lastindex value1 value2..valuen
Ex: set var {orange blue red green}
set var [lreplace $var 2 3 black white]
puts $var result: orange blue black white

lset: setting list item at specific index


syntax: lset listname index value
Ex: set var {orange blue red green}
lset var 0 black
puts $var result: black blue red green

lsort: sorting a list


Ex: set var {orange blue red green}
set var [lsort $var]
Dictionary
A dictionary is an arrangement for mapping values to keys.

Syntax: dict set dictname key value


# or
dict create dictname key1 value1 key2 value2 .. keyn valuen

Ex: dict set colours colour1 red


puts $colours result: colour1 red
dict set colours colour2 green
puts $colours result: colour1 red colour2 green
set colours [dict create colour1 "black" colour2 "white"]
puts $colours result: colour1 black colour2 white
Size of Dict
Syntax: [dict size dictname]
Ex: set colours [dict create colour1 "black" colour2 "white"]
puts [dict size $colours] result:2

Dictionary Iteration
A simple dictionary iteration for printing keys and valued of the dictionary
Ex: set colours [dict create colour1 "black" colour2 "white"]
foreach item [dict keys $colours] {
set value [dict get $colours $item]
puts $value result: black
} white
Value for Key in Dict
Syntax: [dict get $dictname $keyname]
Ex: set colours [dict create colour1 "black" colour2 "white"]
set value [dict get $colours colour1]
puts $value result: black

All Keys in Dict


Syntax: [dict keys $dictname]
Ex: set colours [dict create colour1 "black" colour2 "white"]
set keys [dict keys $colours]
puts $keys result: colour1 colour2
Procedures
Procedures are 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
}
Ex: proc helloWorld {} {
puts "Hello, World!"
}
helloWorld result: Hello, World!

Procedures with Multiple Arguments


Ex: proc add {a b} {
return [expr $a+$b]
}
puts [add 10 30]
result: 40
Procedures with Variable Arguments
Ex: 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}]
puts [avg {70 80 50 }] result: 65 66

Procedures with Default Arguments


Ex: proc add {a {b 100} } {
return [expr $a+$b]
}
puts [add 10 30]
puts [add 10] result: 40 110
Recursive Procedures
Ex: proc factorial {number} {

if {$number <= 1} {

return 1

return [expr $number * [factorial [expr $number - 1]]]

puts [factorial 3] result: 6

puts [factorial 5] 120


File I/O
• Tcl supports file handling with the help of the built in commands open, read, puts, gets, and
close.
• filename is string , which you will use to name your file and access Mode can have one of the
following values:
Opening Files
Tcl uses the open command to open files in Tcl.
Syntax: open fileName accessMode

Closing a File
To close a file, use the close command.
Syntax: close fileName

Writing a File
Puts command is used to write to an open file.
puts $filename "text to write"
Ex: set fp [open "input.txt" w+]
puts $fp "test"
close $fp
Reading a File
the simple command to read from a file:

set file_data [read $fp]

Ex: #!/usr/bin/tclsh

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 result: test


Regular Expressions
• The "regexp" command is used to match a regular expression in Tcl.

• A regular expression is a sequence of characters that contains a search pattern.

Syntax: regexp optionalSwitches patterns searchString fullMatch subMatch1 ... subMatchn

Ex: regexp {([A-Z, a-z]*)} "Tcl Tutorial" a b

puts "Sub Match1: $b” Sub Match1: Tcl


• The following table explains these rules and corresponding use.
Switches for Regex Command
• nocase: Used to ignore case.

• indices: Store location of matched sub patterns instead of matched characters.

• line: New line sensitive matching. Ignores the characters after newline.

• start index: Sets the offset of start of search pattern.

• all: Causes the regular expression to be matched as many times as possible in


the string, returning the total number of matches found.
regsub

Perform substitutions based on regular expression pattern matching

Ex: set mydata {The yellow dog has the bone}


# create a new string; only the first match is replaced.
set newdata [regsub {(yellow|blue)} $mydata green]
puts $newdata result: The green dog has the bone

# replace the data in the same string; all matches are replaced
regsub -all {(yellow|blue)} $mydata red mydata
puts $mydata result: The red dog has the reds
Thank You….!

You might also like