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

TCL - Tool Command Language

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

TCL - Tool Command Language

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 113

TCL- TOOL COMMAND

LANGUAGE
TCL OverView:
• Tcl is a general purpose multi-paradigm system programming language. It is a scripting
language that aims at providing the ability for applications to communicate with each other.
On the other hand, Tk is a cross platform widget toolkit used for building GUI in many
languages.

• Tcl is shortened form of Tool Command Language. John Ousterhout of the University of
California, Berkeley, designed it.

• It is a combination of a scripting language and its own interpreter that gets embedded to the
application, we develop with it.

• Tcl was developed initially for Unix. It was then ported to Windows, DOS, OS/2, and Mac
OSX. Tcl is much similar to other unix shell languages like Bourne Shell (Sh), the C Shell
(csh), the Korn Shell (sh), and Perl.

• It aims at providing ability for programs to interact with other programs and also for acting as
an embeddable interpreter. Even though, the original aim was to enable programs to interact,
you can find full-fledged applications written in Tcl/Tk.
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.

•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 :
Tcl is a general-purpose language and you can find Tcl everywhere. It includes,

•Scalable websites that are often backed by databases.


•High performance web servers build with TclHttpd.
•Tcl with CGI based websites.
•Desktop GUI applications.
•Embedded applications.
ENVIRONMENT SETUP:
If you are willing to set up your environment for Tcl, you need the following two
software applications available on your computer −
• Text Editor
• Tcl Interpreter

Text Editor:
• This will be used to type your program. Examples of a few text editors include Windows
Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or vi.
• The files you create with your text editor are called source files and contain program source
code. The source files for Tcl programs are named with the extension ".tcl".
The Tcl Interpreter:
It is just a small program that enables you to type Tcl commands and have them executed line by
line. It stops execution of a tcl file, in case, it encounters an error unlike a compiler that executes
fully.

#!/usr/bin/tclsh
puts "Hello World!“
Basic Syntax:
RUN using “$tclsh test.tcl”
#!/usr/bin/tclsh OUTPUT:

puts "Hello World!“


Set a 12
Puts $a
RUN using “$tclsh test.tcl”

In Tcl, we use new line or semicolon to terminate the previous line of code. But
semicolon is not necessary, if you are using newline for each command.
Comments:
Comments are like helping text in your Tcl program and the interpreter
ignores them. Comments can be written using a hash_(#) sign in the
beginning. Output:

#!/usr/bin/tclsh
# my first program in Tcl
puts "Hello World!"
Multiline or block comment is written using 'if' with condition '0'. An example is
shown below.

#!/usr/bin/tclsh
if 0 {
my first program in Tcl program Its very simple
}
puts "Hello World!"
Inline comments use ;#. An example is given below.
#!/usr/bin/tclsh
puts "Hello World!" ;# my first print in Tcl program
Output:

IDENTIFIERS:
• A Tcl identifier is a name used to identify a variable, function, or any other user-
defined item.
• An identifier starts with a letter A to Z or a to z or an underscore (_) followed by
zero or more letters, underscores, dollars ($) , and digits (0 to 9).
• Tcl does not allow punctuation characters such as @, and % within identifiers.
• Tcl is a case sensitive_ language.
• For example, input1 and Input1 are different identifiers.
• Examples:
zara abc move_name a_123
myname50 _temp j a23b9 retVal
WhiteSpaces:
• Whitespace is the term used in Tcl to describe blanks, tabs, newline characters,
and comments.
• Whitespace separates one part of a statement from another and enables the
interpreter to identify where one element in a statement, such as puts, ends
and the next element begins. Therefore, in the following statement −

#!/usr/bin/tclsh

puts "Hello World!"

#!/usr/bin/tclsh puts [expr 3 + 2] ;# print sum of the 3 and 2

No whitespace characters are necessary between


3 and +, or between + and 2;
Special Variables:
Sr.No Special Variable & Description
argc
1. Refers to a number of command-line arguments.
argv
2. Refers to the list containing the command-line arguments.
argv0
Refers to the file name of the file being interpreted or the name by which
3. we invoke the script.

env
4. Used for representing the array of elements that are environmental
variables
5. errorCode
Provides the error code for last Tcl error.
6. errorInfo
Provides the stack trace for last Tcl error.
7. tcl_library
Used for setting the location of standard Tcl libraries.
Sr.No Special Variable & Description
tcl_pkgPath
8. Provides the list of directories where packages are generally installed.

9. tcl_patchLevel
Refers to the current patch level of the Tcl interpreter.
tcl_precision
10. Refers to the precision i.e. number of digits to retain when converting to
floating-point numbers to strings. The default value is 12.

tcl_version
11. Returns the current version of the Tcl interpreter.
TCL Commands:
• Tcl is a Tool command language, commands are the most vital part
of the language.
• Tcl commands are built in-to the language with each having its own
predefined function.
• These commands form the reserved words of the language and
cannot be used for other variable naming.
• Tcl command is actually a list of words, with the first word
representing the command to be executed. The next words
represent the arguments
• In order to group the words into a single argument, we enclose
multiple words with "" or {}.

The syntax of Tcl command is as follows −


commandName argument1 argument2... argumentN
#!/usr/bin/tclsh

puts "Hello World!"


In the above code, ‘puts’ is the Tcl command and "Hello World" is the argument1. ,
we have used "" to group two words.

#!/usr/bin/tclsh
puts stdout "Hello, world!"

In the above code, ‘puts’ is the Tcl command, ‘stdout’ is argument1, and "Hello World" is
argument2.
Here, stdout makes the program to print in the standard output device
Command Substitution
In command substitutions, square brackets are used to evaluate the scripts inside
the square brackets.

#!/usr/bin/tclsh

puts [expr 1 + 6 + 9]

Variable Substitution
In variable substitutions, $ is used before the variable name and this returns the
contents of the variable.

#!/usr/bin/tclsh
set a 3
puts $a
Backslash Substitution
These are commonly called escape sequences; with each backslash, followed by a
letter having its own meaning.

#!/usr/bin/tclsh
puts "Hello\nWorld"

Tcl - Data Types


The primitive data-type of Tcl is string

Simple Tcl Objects


• In Tcl, whether it is an integer number, boolean, floating point number, or a string. When
you want to use a variable, you can directly assign a value to it, there is no step of
declaration in Tcl.
• It can transform one data-type to another when required.
#!/usr/bin/tclsh
set myVariable 18
puts $myVariable

The above statement will create a variable name myVariable and stores it as a string
even though, we have not used double quotations. Now, if we try to make an arithmetic
on the variable, it is automatically turned to an integer.

#!/usr/bin/tclsh
set myVariable 18
puts [expr $myVariable + 6 + 9]
String Representations
In Tcl, you need not include double quotes when it's only a single word

#!/usr/bin/tclsh
set myVariable hello
puts $myVariable

When we want to represent multiple strings, we can use either double


quotes or curly braces. It is shown below −

#!/usr/bin/tclsh
set myVariable "hello world“
puts $myVariable
set myVariable {hello world}
puts $myVariable
List:
• List is nothing but a group of elements.
• A group of words either using double quotes or curly braces can be used to
represent a simple list.
• A simple list is shown below −

#!/usr/bin/tclsh
set myVariable {red green blue}
puts [lindex $myVariable 2]
set myVariable "red green blue"
puts [lindex $myVariable 1]
Associative Array:
• Associative arrays have an index (key) that is not necessarily an integer.
• It is generally a string that acts like key value pairs.
• A simple example is shown below −

#!/usr/bin/tclsh
set marks(english) 80
puts $marks(english)
set marks(mathematics) 90
puts $marks(mathematics)
Handles:

Tcl handles are commonly used to represent files and graphics objects. These can include
handles to network requests and also other channels like serial port communication,
sockets, or I/O devices.

set myfile [open "filename" r]


Tcl – Variables:
• The name of variables can contain any characters and length. You can even have
white spaces by enclosing the variable in curly braces, but it is not preferred.

• The set command is used for assigning value to a variable. The syntax for set command is,
• set variableName value

Dynamic Typing
• Tcl is a dynamically typed language.
• The value of the variable can be dynamically converted to the required type
when required
#!/usr/bin/tclsh
set variableA "10“
puts $variableA
set sum [expr $variableA +20];
puts $sum
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.

#!/usr/bin/tclsh
set variableA "10"
set result [expr $variableA / 9];
puts $result
set result [expr $variableA / 9.0];
puts $result
set variableA "10.0"
set result [expr $variableA / 9];
puts $result
you can change the precision by using tcl_precision special variable. It is
shown below

#!/usr/bin/tclsh
set variableA "10"
set tcl_precision 5
set result [expr $variableA / 9.0];
puts $result
Tcl - 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
Assume variable ‘A’ holds 10 and variable ‘B’ holds 20, then −

Operator Description Example


+ Adds two operands A + B will give 30
Subtracts second operand
- A - B will give -10
from the first
* Multiplies both operands A * B will give 200
Divides numerator by de-
/ B / A will give 2
numerator

Modulus Operator and


% remainder of after an B % A will give 0
integer division
#!/usr/bin/tclsh
set a 21
set b 10
set c [expr $a + $b]
puts "Line 1 - Value of c is $c\n"
set c [expr $a - $b]
puts "Line 2 - Value of c is $c\n"
set c [expr $a * $b]
puts "Line 3 - Value of c is $c\n"
set c [expr $a / $b]
puts "Line 4 - Value of c is $c\n"
set c [expr $a % $b]
puts "Line 5 - Value of c is $c\n"
Relational Operators
Following table shows all the relational operators supported by Tcl language.
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example


== Checks if the values of two operands are equal or not, if yes (A == B) is not true
then condition becomes true
!= Checks if the values of two operands are equal or not, if (A != B) is true.
values are not equal then condition becomes true.
> Checks if the value of left operand is greater than the value (A > B) is not true
of right operand, if yes then condition becomes true
< Checks if the value of left operand is less than the value of (A < B) is true
right operand, if yes then condition becomes true
>= Checks if the value of left operand is greater than or equal to (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 or equal to the (A <= B) is true
value of right operand, if yes then condition becomes true.
Logical Operators
Following table shows all the logical operators supported by Tcl language. Assume
variable A holds 1 and variable B holds 0, then −

&& Called Logical AND operator. If both the operands are non- (A && B) is false
zero, then condition becomes true.
|| Called Logical OR Operator. If any of the two operands is non- (A || B) is true.
zero, then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state
of its operand. If a condition is true then Logical NOT operator
will make false
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth
tables for &, |, and ^ are as follows −

p q p&q p|q p^q


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Assume if A = 60; and B = 13; now in binary format they will be as


follows −
A = 0011 1100
B = 0000 1101
----------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
The Bitwise operators supported by Tcl language are listed below:

Operator Description Example


(A & B) will give
Binary AND Operator copies a bit to the result if it exists in
& 12, which is 0000
both operands.
1100

(A | B) will give
Binary OR Operator copies a bit if it exists in either
| 61, which is 0011
operand.
1101

(A ^ B) will give
Binary XOR Operator copies the bit if it is set in one
^ 49, which is 0011
operand but not both.
0001

Binary Left Shift Operator. The left operands value is A << 2 will give
<< moved left by the number of bits specified by the right 240, which is
operand. 1111 0000

Binary Right Shift Operator. The left operands value is A >> 2 will give
>> moved right by the number of bits specified by the right 15, which is 0000
operand. 1111
Ternary Operator

Operator Description Example


If Condition is true?
?: Ternary Then value X :
Otherwise value Y
Category Operator Associativity
Unary +- Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= 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

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.
Tcl - Decisions
• Decision making structures require that the programmer specifies one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false

• Tcl language uses the expr command internally and hence it’s not required for us
to use expr statement explicitly
Tcl - If Statement
An if statement consists of a Boolean expression followed by one or more
statements.
Syntax
The syntax of an 'if' statement in Tcl language is −
if {boolean_expression} {
# statement(s) will execute if the Boolean expression
is true
•} Tcl language uses the expr command internally and hence it's not required
for us to use expr statement explicitly.

#!/usr/bin/tclsh
set a 10
#check the boolean condition using if statement
if { $a < 20 } {
# if condition is true then print the following
puts "a is less than 20"
}
puts "value of a is : $a"
Tcl - If else Statement
• An if statement can be followed by an optional else statement, which executes
when the Boolean expression is false.

Syntax:

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
}
The syntax of an 'if...else if...else' statement in Tcl language is −

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 }
#!/usr/bin/tclsh
set a 100
#check the boolean condition
if {$a < 20 } {
#if condition is true then print the following
puts "a is less than 20"
} else {
#if condition is false then print the following
puts "a is not less than 20"
}
puts "value of a is : $a"
Tcl - Nested If Statement

It is always legal in Tcl to nest if-else statements, which means you can use one if or else if statement
inside another if or else if statement(s).
Syntax

nested if statement is as follows −


The syntax for a
if { boolean_expression 1 } {
# Executes when the boolean expression 1 is true
if {boolean_expression 2} {
# Executes when the boolean expression 2 is true
}
}
#!/usr/bin/tclsh
set a 100
set b 200
# check the boolean condition
if { $a == 100 } {
# if condition is true then check the
following
if { $b == 200 } {
#if condition is true then print the
following puts "Value of a is 100 and b is
200"
}
}
puts "Exact value of a is : $a"
puts "Exact value of b is : $b"
Tcl - 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.
The syntax for unquoted switch statement in Tcl language is as follows −

switch switchingString { The following rules apply to a switch statement −


matchString1 {
body1 •The switchingString is used in a switch statement; used
} between the different blocks by comparing to the
matchString2 { matchString.
body2 •You can have any number of matchString blocks within a
} switch.
... •A switch statement can have an optional default block,
matchStringn { which must appear at the end of the switch. The default
bodyn case can be used for performing a task when none of the
} cases is true.
}
#!/usr/bin/tclsh
set grade C;
switch $grade
A{
puts "Well done!"
}
B{
puts "Excellent!"
}
C{
puts "You passed!"
}
F{
puts "Better try again"
}
default {
puts "Invalid grade"
}
puts "Your grade is $grade"
Tcl - Nested Switch Statement
It is possible to have a switch as part of the statement sequence of an outer switch. Even if
the case constants of the inner and outer switch contain common values, no conflicts will arise
SYNTAX:
switch switchingString {
matchString1 {
body1
switch switchingString {
matchString1 {
body1
} matchString2 {
body2
}
...

matchStringn {
bodyn
}
}
}
matchString2 {
body2
}
...
matchStringn {
bodyn
}
}
#!/usr/bin/tclsh
set a 100
set b 200
switch $a {
100 {
puts "This is part of outer
switch" switch $b {
200 {
puts "This is part of inner
switch!"
}
}
}
}
puts "Exact value of a is : $a"
puts "Exact value of a is : $b"
The ? : Operator

This operator is called ternary operator.


Syntax:

Exp1 ? Exp2 : Exp3;

Tcl - Loops
A loop statement allows us to execute a statement or group of statements multiple times
and following is the general form of a loop statement in most of the programming
languages −
Tcl - While Loop
A while loop statement in Tcl language repeatedly executes a target statement
as long as a given condition is true.
Syntax:
The syntax of a while loop in Tcl language is −

while {condition} {
statement(s)
}
#!/usr/bin/tclsh
set a 10
#while loop execution
while { $a < 20 } {
puts "value of a: $a"
incr a
}
Tcl - For Loops
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);
}
#!/usr/bin/tclsh
# for loop execution
for { set a 10} {$a < 20} {incr a} {
puts "value of a: $a"
}
Tcl - Nested Loops
Tcl allows to use one loop inside another loop.
Syntax:
The syntax for a nested for loop statement in Tcl language is as follows −

for {initialization} {condition} {increment} {


for {initialization} {condition} {increment} {
statement(s);
}
statement(s);
}
The syntax for a nested while loop statement in Tcl language is as follows
while {condition} {
while {condition} {
statement(s);
}
statement(s);
}
#!/usr/bin/tclsh
set j 0;
for {set i 2} {$i<20} {incr i} {
for {set j 2} {$j <= [expr $i/$j] } {incr j} {
if { [expr $i%$j] == 0 } {
break
}
}
if {$j >[expr $i/$j] } {
puts "$i is prime“
}
}
Tcl - Arrays
An array is a systematic arrangement of a group of elements using indices.
The syntax for the conventional array is shown below.

set ArrayName(Index) value

#!/usr/bin/tclsh
set languages(0) Tcl
set languages(1) "C Language"
puts $languages(0)
puts $languages(1)
Size of Array
The syntax for calculating size array is shown below.
[array size variablename]

#!/usr/bin/tclsh
set languages(0) Tcl
set languages(1) "C Language"
puts [array size languages]
Array Iteration

#!/usr/bin/tclsh
set languages(0) Tcl
set languages(1) "C Language"
for { set index 0 } { $index < [array size languages] } { incr index }
{
puts "languages($index) : $languages($index)" }
Indices of Array
The syntax for retrieving indices of array is shown below.

[array names variablename]

#!/usr/bin/tclsh
set personA(Name) "Dave"
set personA(Age) 14
puts [array names personA]
Iteration of Associative Array

#!/usr/bin/tclsh
set personA(Name) "Dave"
set personA(Age) 14
foreach index [array names personA] {
puts "personA($index): $personA($index)" }
Tcl - Strings

String Escape Sequence:

Escape
Meaning
sequence
\\ \ character
\' ' character
\" " character
\? ? character
\a Alert or bell
\b Backspace
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
#!/usr/bin/tclsh
puts "Hello\tWorld\n\nwelcome\t\”TCL SCRIPTING\”";
String Command
Sr.No. Methods & Description
compare string1 string2
1 Compares string1 and string2 lexographically. Returns 0 if equal, -1 if string1 comes
before string2, else 1.

2 first string1 string2


Returns the index first occurrence of string1 in string2. If not found, returns -1.

3 index string index


Returns the character at index.

4 last string1 string2


Returns the index last occurrence of string1 in string2. If not found, returns -1.

5 length string
Returns the length of string.

6 match pattern string


Returns 1 if the string matches the pattern.

7 range string index1 index2


Return the range of characters in string from index1 to index2.
Sr.No. Methods & Description

8 tolower string
Returns the lowercase string.

9 toupper string
Returns the uppercase string.

10 trim string ?trimcharacters?


Removes trimcharacters in both ends of string. The default trimcharacters is whitespace.

trimleft string ?trimcharacters?


11 Removes trimcharacters in left beginning of string. The default trimcharacters is
whitespace.

12 trimright string ?trimcharacters?


Removes trimcharacters in left end of string. The default trimcharacters is whitespace.

wordend findstring index


13 Return the index in findstring of the character after the word containing the character at
index.
wordstart findstring index
14 Return the index in findstring of the first character in the word containing the character at
index.
String Comparison

#!/usr/bin/tclsh
set s1 "Hello"
set s2 "World"
set s3 "World"
puts [string compare $s1 $s2]
if {[string compare $s2 $s3] == 0} {
puts "String \'s1\' and \'s2\' are same.";
}
if {[string compare $s1 $s2] == -1} {
puts "String \'s1\' comes before \'s2\'.";
}
if {[string compare $s2 $s1] == 1} {
puts "String \'s2\' comes after \'s1\'.";
}
Index of String

#!/usr/bin/tclsh
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]
puts "Word end index in s1"
puts [string wordend $s1 20]
puts "Word start index in s1"
puts [string wordstart $s1 20]
Length of String

#!/usr/bin/tclsh
set s1 "Hello World"
puts "Length of string s1"
puts [string length $s1]

Handling Cases

#!/usr/bin/tclsh
set s1 "Hello World"
puts "Uppercase string of s1“
puts [string toupper $s1]
puts "Lowercase string of s1"
puts [string tolower $s1]
Trimming Characters

#!/usr/bin/tclsh
set s1 "Hello World"
set s2 "World"
puts "Trim right $s2 in $s1"
puts [string trimright $s1 $s2]
set s2 "Hello"
puts "Trim left $s2 in $s1"
puts [string trimleft $s1 $s2]
set s1 " Hello World "
set s2 " "
puts "Trim characters s1 on both sides of s2"
puts [string trim $s1 $s2]
Matching Strings

#!/usr/bin/tclsh
set s1 "[email protected]"
set s2 "*@*.com"
puts "Matching pattern s2 in s1"
puts [string match "*@*.com" $s1 ]
puts "Matching pattern tcl in s1"
puts [string match {tcl} $s1]

Append Command

#!/usr/bin/tclsh
set s1 "Hello"
append s1 " World"
puts $s1
Format command

Specifier Use
%s String representation
%d Integer representation
%f Floating point representation
%e Floating point representation with mantissa-exponent form
%x Hexa decimal representation

#!/usr/bin/tclsh
puts [format "%f" 43.5]
puts [format "%e" 43.5]
puts [format "%d %s" 4 tuts]
puts [format "%s" "Tcl Language"]
puts [format "%x" 40]
Scan command
Scan command is used for parsing a string based to the format specifier.

#!/usr/bin/tclsh
puts [scan "90" {%[0-9]} m]
puts [scan "abc" {%[a-z]} m]
puts [scan "abc" {%[A-Z]} m]
puts [scan "ABC" {%[A-Z]} m]
Tcl – Lists:
Creating a List
The general syntax for list is given below −

set listName { item1 item2 item3 .. itemn }


# or
set listName [list item1 item2 item3]
# or
set listName [split "items separated by a character" split_character]
#!/usr/bin/tclsh
set colorList1 {red green blue}
set colorList2 [list red green blue]
set colorList3 [split "red_green_blue" _]
puts $colorList1
puts $colorList2
puts $colorList3
Appending Item to a List

The syntax for appending item to a list is given below −


append listName split_character value
# or lappend listName value
#!/usr/bin/tclsh
set var orange
append var " " "blue"
lappend var "red"
lappend var "green"
puts $var

Length of List
The syntax for length of list is given below −

llength listName
#!/usr/bin/tclsh
set var {orange blue red green}
puts [llength $var]
List Item at Index

lindex listname index


#!/usr/bin/tclsh
set var {orange blue red green}
puts [lindex $var 1]

Insert Item at Index:


The syntax for inserting list items at specific index is given below.

linsert listname index value1 value2..valuen


#!/usr/bin/tclsh
set var {orange blue red green}
set var [linsert $var 3 black white]
puts $var
Replace Items at Indices
The syntax for replacing list items at specific indices is given below −
lreplace listname firstindex lastindex value1 value2..valuen

#!/usr/bin/tclsh
set var {orange blue red green}
set var [lreplace $var 2 3 black white]
puts $var

Set Item at Index


The syntax for setting list item at specific index is given below −

lset listname index value


#!/usr/bin/tclsh
set var {orange blue red green} l
set var 0 black
puts $var
Transform List to Variables
The syntax for copying values to variables is given below −

lassign listname variable1 variable2.. variablen


#!/usr/bin/tclsh
set var {orange blue red green}
lassign $var colour1 colour2
puts $colour1
puts $colour2
Sorting a List
The syntax for sorting a list is given below −
lsort listname
#!/usr/bin/tclsh
set var {orange blue red green}
set var [lsort $var]
puts $var
Tcl – Dictionary:
A dictionary is an arrangement for mapping values to keys.
The syntax for the conventional dictionary is shown below −

dict set dictname key value


# or
dict create dictname key1 value1 key2 value2 .. keyn valuen
#!/usr/bin/tclsh
dict set colours colour1 red
puts $colours
dict set colours colour2 green
puts $colours
set colours [dict create colour1 "black" colour2
"white"]
puts $colours
Size of Dict:
The syntax for getting size of dict is shown below −
[dict size dictname]

#!/usr/bin/tclsh
set colours [dict create colour1 "black" colour2 "white"]
puts [dict size $colours]
Value for Key in Dict
The syntax for retrieving value for key in dict is shown below

[dict get $dictname $keyname]

#!/usr/bin/tclsh
set colours [dict create colour1 "black" colour2 "white"]
set value [dict get $colours colour1]
puts $value
All Keys in Dict
The syntax for retrieving all keys in dict is shown below −
[dict keys $dictname]

#!/usr/bin/tclsh
set colours [dict create colour1 "black" colour2 "white"]
set keys [dict keys $colours]
puts $keys
All Values in Dict
The syntax for retrieving all values in dict is shown below −

[dict values $dictname]


#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]


set values [dict values $colours]
puts $values
Dictionary Iteration
A simple dictionary iteration for printing keys and valued of the dictionary is
shown below −

#!/usr/bin/tclsh
set colours [dict create colour1 "black" colour2 "white"]
foreach item [dict keys $colours] {
set value [dict get $colours $item]
puts $value }
Key Exists in Dict
The syntax for checking if a key exists in dict is shown below −

[dict exists $dictname $key]

#!/usr/bin/tclsh

set colours [dict create colour1 "black" colour2 "white"]


set result [dict exists $colours colour1]
puts $result
Tcl - Procedures
• 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.
• Procedures are equivalent to the functions used in many programming languages and are
made available in Tcl with the help of proc command.
The syntax of creating a simple procedure is shown below −

proc procedureName {arguments} {


body
}
#!/usr/bin/tclsh
proc helloWorld {} {
puts "Hello, World!"
} helloWorld
Procedures with Multiple Arguments

#!/usr/bin/tclsh
proc add {a b} {
return [expr $a+$b]
}
puts [add 10 30]
Procedures with Variable Arguments

#!/usr/bin/tclsh

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 }]
Procedures with Default Arguments
• Default arguments are used to provide default values that can be used if no value is
provided.
• An example for procedure with default arguments, which is sometimes referred as
implicit arguments is shown below −

#!/usr/bin/tclsh
proc add {a {b 100} } {
return [expr $a+$b]
}
puts [add 10 30]
puts [add 10]
Recursive Procedures
#!/usr/bin/tclsh
proc factorial {number} {
if {$number <= 1} {
return 1
}
return [expr $number * [factorial [expr $number - 1]]]
}
puts [factorial 3]
puts [factorial 5]
FILE – I/O
• Tcl supports file handling with the help of the built in commands open, read, puts,
gets, and close.
• A file represents a sequence of bytes, does not matter if it is a text file or binary file.

Opening Files:
• Tcl uses the open command to open files in Tcl.
• The syntax for opening a file is as follows −

open fileName accessMode


ACCESS MODES:
Sr.No. Mode & Description
r
1 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
2 Opens a text file for writing, if it does not exist, then a new file is created else existing file is
truncated.

a
3 Opens a text file for writing in appending mode and file must exist. Program will start appending
content in the existing file content.

4 r+
Opens a text file for reading and writing both. File must exist already.

w+
5 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+
6 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.
Closing a File
• To close a file, use the close command.
• The syntax for close is as follows −

close fileName

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

• In most cases, the files need not be closed explicitly; they are closed
automatically when File objects are terminated automatically.
Writing a File
• Puts command is used to write to an open file.

puts $filename "text to write"

#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test"
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
Reading a File
• The simple command to read from a file

set file_data [read $fp]

#!/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
another example for reading file till end of file line by line −

#!/usr/bin/tclsh
set fp [open "input.txt" w+]
puts $fp "test\ntest"
close $fp
set fp [open "input.txt" r]
while { [gets $fp data] >= 0 }
{ puts $data
}
close $fp
Tcl - Error Handling
• Error handling in Tcl is provided with the help of error and catch commands.

Error syntax
error message info code
In the above error command syntax,
• message is the error message,
• info is set in the global variable errorInfo and
• code is set in the global variable errorCode.

Catch Syntax
catch script resultVarName
In the above catch command syntax,
• script is the code to be executed,
• resultVarName is variable that holds the error or the result.
• The catch command returns 0 if there is no error, and 1 if there is an error.
#!/usr/bin/tclsh
proc Div {a b} {
if {$b == 0} {
error "Error generated by error" "Info String for error"
401
} else {
return [expr $a/$b]
}
}
if {[catch {puts "Result = [Div 10 0]"} errmsg]} {
puts "ErrorMsg: $errmsg"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
}
if {[catch {puts "Result = [Div 10 2]"} errmsg]} {
puts "ErrorMsg: $errmsg“
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
}
#!/usr/bin/tclsh
catch {set file [open myNonexistingfile.txt]} result
puts "ErrorMsg: $result"
puts "ErrorCode: $errorCode"
puts "ErrorInfo:\n$errorInfo\n"
Tcl - Built-in Functions
Tcl provides a number of built-in functions (procedures) for various operations. This
includes −
•Functions for list handling.

•Functions for string handling.

•Functions for array handling.

•Functions for dictionary handling.

•Functions for File I/O handling.

•Functions for Math operations.

•Functions for System operations.


Math Functions
Sr.No. Method & Description

1 abs arg
Calculates the absolute value of arg.

2 acos arg
Calculates the arccosine of arg.

3 asin arg
Calculates the arcsine of arg.

4 atan arg
Calculates the arctangent of arg.

5 atan2 y x
Calculates the arctangent of the quotient of its arguments(y/x).

6 ceil arg
Calculates the smallest integer greater than or equal to a number.

7 cos arg
Calculates the cosine of arg.
Sr.No. Method & Description

8 cosh arg
Calculates the hyperbolic cosine of arg.
double arg
9 Calculates if arg is a floating-point value, returns arg, otherwise converts arg to
floating-point and returns the converted value.

10 exp arg
Calculates an exponential function (e raised to the power of arg).

11 floor arg
Calculates the largest integer less than or equal to arg.
fmod x y
12 Calculates the floating-point remainder of the division of x by y. If y is 0, an error is
returned.

13 hypot x y
Calculates the length of the hypotenuse of a right-angled triangle sqrt(x*x+y*y).
int arg
14 Calculates if arg is an integer value of the same width as the machine word, returns
arg, otherwise converts arg to an integer.
Sr.No. Method & Description

15 log arg
Calculates the natural logarithm of arg.

16 log10 arg
Calculates the base 10 logarithm of arg.
pow x y
17 Calculates the value of x raised to the power y. If x is negative, y must be an integer
value.

18 rand
Calculates a pseudo-random number between 0 and 1.

19 round arg
Calculates the value of arg rounded to the nearest integer.

20 sin arg
Calculates the sine of arg.

21 sinh arg
Calculates the hyperbolic sine of arg.
Sr.No. Method & Description

21 sinh arg
Calculates the hyperbolic sine of arg.

22 sqrt arg
Calculates the square root of arg. arg must be positive.
srand arg
23 Calculates a pseudo-random number between 0 and 1. The arg, which must be an integer, is used
to reset the seed for the random number generator of rand.

24 tan arg
Calculates the tangent of arg.

25 tanh arg
Calculates the hyperbolic tangent of arg.
wide arg
26 Calculates integer value at least 64-bits wide (by sign-extension if arg is a 32-bit number) for arg if
it is not one already.
#!/usr/bin/tclsh
namespace import ::tcl::mathfunc::*
puts [tan 10]
puts [pow 10 2]
puts [ceil 10.34]
puts [hypot 10 20]
puts [srand 45]
puts [log 10]
System Functions
The important system functions in Tcl includes,

•clock − seconds function, which returns current time in seconds.


•clock − format function, which formats the seconds into date and
time.
•clock − scan function, which scans the input string and converts it
into seconds.
•open − function, which is used to open a file.
•exec − function, which is used to execute a system command.
•close − function, which is used to close a file
#!/usr/bin/tclsh
#get seconds
set currentTime [clock seconds]
puts $currentTime
#get format
puts "The time is: [clock format $currentTime -format %H:
%M:%S]"
puts "The date is: [clock format $currentTime -format %D]"
set date "Jun 15, 2014"
puts [clock scan $date -format {%b %d, %Y}]
puts [exec ls] ; puts [exec dir] ;
set a [open input.txt] ; puts [read $a];
puts $a
close $a
The following table provides the list strings that can be used to format the date and time
Sr.No. Format & Description

1 %a
Day in short form, eg:Sun.

2 %A
Day in full form eg:Sunday.

3 %b
Month in short form.

4 %B
Month in full form.

5 %d
Day of month.

6 %j
Julian day of year.

7 %m
Month in number.
Sr.No. Format & Description

8 %y
Year in two digits.
9 %Y
Year in four digits.
10 %H
Hour in 24 hour clock.
11 %I
Hour in 12 hour clock.
12 %M
Minutes.
13 %S
Seconds.
14 %p
AM or PM.
Sr.No. Format & Description
15 %D
Date in number, mm /dd/yy.
16 %r
Time in 12 hour clock.
17 %R
Time in 24 hour clock without seconds.
18 %T
Time in 24 hour clock with seconds.
%Z
19 Time Zone Name like GMT, IST, EST and so
on.
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.
• It consists of multiple rules.
Sr.No. Rule & Description

x
1
Exact match.
[a-z]
2
Any lowercase letter from a-z.
.
3
Any character.
^
4
Beginning string should match.
$
5
Ending string should match.
Sr.No. Rule & Description
\^
6 Backlash sequence to match special character
^.Similarly you can use for other characters.
()
7 Add the above sequences inside parenthesis to make a
regular expression.
x*
8 Should match 0 or more occurrences of the preceding
x.
x+
9 Should match 1 or more occurrences of the preceding
x.
[a-z]?
10
Should match 0 or 1 occurrence of the preceding x.
Sr.No. Rule & Description

{digit}
11 Matches exactly digit occurrences of previous
regex expression. Digit that contains 0-9.

| -Alternative
12
Must match one alternative

{digit1,digit2}
Occurrences matches the range between digit1
13
and digit2 occurrences of previous regex
expression.
Syntax
The syntax for regex is given below −

regexp optionalSwitches patterns searchString fullMatch subMatch1 ...


subMatchn
Here,
• regex is the command

• Search string is the actual string on which the regex is performed.

• Full match is any variable to hold the result of matched regex result.

• Submatch1 to SubMatchn are optional subMatch variable that holds the result of sub match
patterns.
#!/usr/bin/tclsh
regexp {([A-Za-z]*)} "Tcl Tutorial" a b
puts "Full Match: $a"
puts "Sub Match1: $b"
Multiple Patterns:
• This is example pattern for any alphabets followed by any character followed by
any alphabets.

#!/usr/bin/tclsh
regexp {([A-Za-z]*).([A-Za-z]*)} "Tcl Tutorial" a b c
puts "Full Match: $a"
puts "Sub Match1: $b“
puts "Sub Match2: $c"
Switches for Regex Command
The list of switches available in Tcl are,
•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.
•Marks the end of switches
#!/usr/bin/tclsh
regexp -nocase {([A-Z]*.([A-Z]*))} "Tcl Tutorial" a b c
puts "Full Match: $a"
puts "Sub Match1: $b“
puts "Sub Match2: $c"
#!/usr/bin/tclsh

regexp -nocase -line -- {([A-Z]*.([A-Z]*))} "Tcl \nTutorial" a b


puts "Full Match: $a"

puts "Sub Match1: $b"

regexp -nocase -start 4 -line -- {([A-Z]*.([A-Z]*))} "Tcl \nTutorial" a b

puts "Full Match: $a" puts "Sub Match1: $b"

You might also like