0% found this document useful (0 votes)
37 views99 pages

Scripting Languages Unit V TCL Department of Information Technology

The document provides an overview of the Tool Command Language (TCL), highlighting its structure, syntax, and key features such as control flow, data types, and variable scope. It explains TCL's simplicity and versatility for scripting and application control, along with examples of its commands and procedures. Additionally, the document outlines the use of global and local variables, as well as control flow commands like 'if' for conditional execution.

Uploaded by

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

Scripting Languages Unit V TCL Department of Information Technology

The document provides an overview of the Tool Command Language (TCL), highlighting its structure, syntax, and key features such as control flow, data types, and variable scope. It explains TCL's simplicity and versatility for scripting and application control, along with examples of its commands and procedures. Additionally, the document outlines the use of global and local variables, as well as control flow commands like 'if' for conditional execution.

Uploaded by

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

Scripting Languages

Unit V
TCL
Department of Information Technology

Prepared by Ms S.Rama Devi

BVRIT HYDERABAD College of Engineering for Women


Contents
• TCL Structure,
• syntax,
• Variables and Data in TCL,
• Control Flow,
• Data Structures,
• input/output,
• procedures,
• strings,
• patterns,
• files,
BVRIT HYDERABAD College of Engineering for Women
Introduction to TCL
• TCL stands for “Tool Command Language” and is pronounced “tickle”; is
a simple scripting language for controlling and extending applications.
• TCL is a radically simple open-source interpreted programming language
that provides common facilities such as variables, procedures, and
control structures as well as many useful features that are not found in
any other major language.
• TCL runs on almost all modern operating systems such as Unix,
Macintosh, and Windows (including Windows Mobile).
• While TCL is flexible enough to be used in almost any application
imaginable, it does excel in a few key areas, including automated
interaction with external programs, embedding as a library into
application programs, language design, and general scripting.
BVRIT HYDERABAD College of Engineering for Women
• TCL was created in 1988 by John Ousterhout and is distributed under
a BSD style license (which allows you everything GPL does, plus
closing your source code).
• The first major GUI extension that works with TCL is TK, a toolkit that
aims to rapid GUI development.
• That is why TCL is now more commonly called TCL/TK. The language
features far-reaching introspection, and the syntax, while simple2, is
very different from the Fortran/Algol/C++/Java world.
• Although TCL is a string-based language there are quite a few
object-oriented extensions.

BVRIT HYDERABAD College of Engineering for Women


• Tcl was originally developed as a reusable command language for
experimental computer aided design (CAD) tools.

• The interpreter is implemented as a C library that could be linked into


any application.

• It is very easy to add new functions to the TCL interpreter, so it is an


ideal reusable "macro language" that can be integrated into many
applications.

BVRIT HYDERABAD College of Engineering for Women


TCL Structure
• The TCL language has a tiny syntax - there is only a single command
structure, and a set of rules to determine how to interpret the
commands.
• Other languages have special syntaxes for control structures (if, while,
repeat...) - not so in TCL. All such structures are implemented as
commands.
• There is a runtime library of compiled ’C’ routines, and the ’level’ of the
GUI interface is quite high.

BVRIT HYDERABAD College of Engineering for Women


Comments
• If the first character of a command is #, it is a comment.
• TCL commands: TCL commands are just words separated by spaces.
Commands return strings, and arguments are just further words.
command argument command
• Argument : Spaces are important
expr 5*3 has a single
argument expr 5 * 3 has three arguments
• TCL commands are separated by a new line, or a semicolon, and
arrays are indexed by text
set a(a\ text\ index) 4

BVRIT HYDERABAD College


BVRIT HYDERABAD College ofof Engineering
Engineering for Women
for Women
Syntax
• Syntax is just the rules how a language is structured.
• A simple syntax of English could say(Ignoring punctuation for the
moment) A text consists of one or more sentences, A sentence
consists of one or more words’
• Simple as this is, it also describes Tcl's syntax very well - if you say
"script" for "text", and "command" for "sentence".
• There's also the difference that a Tcl word can again contain a script or
a command. So if {$x < 0} {set x 0} is a command consisting of three
words: if, a condition in braces, a command (also consisting of three
words) in braces.

BVRIT HYDERABAD College of Engineering for Women


Variable Substitution
Tcl - Data Types When we want to represent multiple strings,
we can use either double quotes or curly braces.
List
• An array is a systematic arrangement of a group of elements
using indices. The syntax for the conventional array is shown
below.
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.
Size of Array
[array size
variablename]

set languages(0) Tcl


set languages(1) "C Language"
puts [array size languages]
List Functions
• lappend
• llength
• lindex
• linsert
• lreplace
• lset
1. Write a TCL script to find the factorial of a number
2. Write a TCL script that multiplies the numbers from 1 to 10
3. Write a TCL script for Sorting a list using a comparison function
4. Write a TCL script to (i)create a list (ii) append elements to the list (iii)Traverse the list
(iv)Concatenate the list
5. Write a TCL script to comparing the file modified times.
6. Write a TCL script to Copy a file and translate to native format.
• Take this for example is a well-formed Tcl command: it calls Take (which
must have been defined before) with the three arguments "this", "for",
and "example".
• It is up to the command how it interprets its arguments, e.g. puts
acos(-1) will write the string "acos(-1)" to the stdout channel, and
return the empty string "", while expr acos(-1) will compute the arc
cosine of -1 and return 3.14159265359 (an approximation of Pi), or
string length acos(-1) will invoke the string command, which again
dispatches to its length sub-command, which determines the length of
the second argument and returns 8.
• A Tcl script is a string that is a sequence of commands, separated by
newlines or semicolons.

BVRIT HYDERABAD College of Engineering for Women


• A command is a string that is a list of words, separated by blanks. The first
word is the name of the command; the other words are passed to it as its
arguments.
• In Tcl, "everything is a command" - even what in other languages would be
called declaration, definition, or control structure.
• A command can interpret its arguments in any way it wants - in particular, it
can implement a different language, like expression.
• A word is a string that is a simple word, or one that begins with { and ends
with the matching } (braces), or one that begins with " and ends with the
matching ".
• Braced words are not evaluated by the parser. In quoted words,
substitutions can occur before the command is called: $[A-Za-z0-9_]+
substitutes the value of the given variable.

BVRIT HYDERABAD College of Engineering for Women


• Or, if the variable name contains characters outside that regular
expression, another layer of bracing helps the parser to get it right
puts "Guten Morgen, ${Schuler}!“
• If the code would say $Schuler, this would be parsed as the value of
variable $Sch, immediately followed by the constant string Schüler.
• (Part of) a word can be an embedded script: a string in [] brackets
whose contents are evaluated as a script (see above) before the
current command is called. In short: Scripts and commands contain
words.
• Words can again contain scripts and commands. (This can lead to
words more than a page long...)

BVRIT HYDERABAD College of Engineering for Women


• Arithmetic and logic expressions are not part of the Tcl language itself,
but the language of the expr command (also used in some arguments
of the if, for, while commands) is basically equivalent to C's expressions,
with infix operators and functions.

BVRIT HYDERABAD College of Engineering for Women


Variables and Data in TCL
• As noted above, by default, variables defined inside a procedure are
"local" to that procedure.
• And the argument variables of the procedure contain local "copies" of
the argument data used to invoke the procedure.
• These local variables cannot be seen elsewhere in the script, and they
only exist while the procedure is being executed.
• In the "getAvg" procedure above, the local variables created in the
procedure are "n" "r" and "avg".
• TCL provides two commands to change the scope of a variable inside
a procedure, the "global" command and the "upvar" command.

BVRIT HYDERABAD College of Engineering for Women


• The "global" command is used to declare that one or more variables
are not local to any procedure.
• The value of a global variable will persist until it is explicitly changed.
So, a variable which is declared with the "global" command can be
seen and changed from inside any procedure which also declares
that variable with the "global" command.
• Variables which are defined outside of any procedure are
automatically global by default.
• The TCL "global" command declares that references to a given
variable should be global rather than local.
• However, the "global" command does not create or set the variable
… this must be done by other means, most commonly by the TCL
"set" command.

BVRIT HYDERABAD College of Engineering for Women


• For example,
here is an proc getAvgN { rList } \
adjusted version {
of our averaging global currentLength
procedure which set currentLength [llength $rList]
saves the input if {!$currentLength} {return 0.0}
list length in the set avg 0.0
global variable foreach r $rList \
"currentLength" {
so that other
set avg [expr $avg + $r]
parts of the
script can access }
this information set avg [expr $avg/double($currentLength)]
after "getAvgN" return $avg
is called: }

BVRIT HYDERABAD College of Engineering for Women


• A procedure can use global variables for persistent storage of
information, including the possibility to test whether the procedure
has been called previously; this is useful for procedures that might
need to perform a one-time initialization.
• In these cases, a procedure will use a global variable which is not set
anywhere else. This means, the first time the procedure is called, the
global variable will not yet exist (recall that the "global" statement
declares that a variable will be accessed as a global variable, but it
does not define or create the variable itself).
• The TCL command "info exists" will evaluate to true if the given
variable exists.

BVRIT HYDERABAD College of Engineering for Women


• For example, suppose we wanted to make a version of our procedure
"getAvg" which keeps an internal count of how many times it has been
called.
• In this version, we use a global variable named "callCount_getAvg" to
keep track of the number of times "getAvg" is called. Because this
global variable will actually be used to store information for the
specific use of the "getAvg" procedure, we need to choose a global
variable name which will not be used for a similar purpose in some
other procedure. The first time "getAvg" is called, the global variable
does not yet exist, and must be set to zero.

BVRIT HYDERABAD College of Engineering for Women


• A more flexible way to manipulate persistent data is to use global
arrays rather than scalar variables.
• For example, instead of the procedure-specific scalar variable
"callCount_getAvg" used above, we can use a general-purpose array
"callCount()" which could be used to record the call counts of any
number of procedures, by using the procedure name as the array
index.
• Many nmrWish TCL scripts use global arrays in this fashion, to simplify
the sharing of many data values between procedures. Here is a
version of the "getAvg" procedure with the call count tallied in a
global array location … note that an array is declared global simply by
listing its name in a "global" command, exactly as for a scalar variable;
no ( ) parenthesis or index values are used.

BVRIT HYDERABAD College of Engineering for Women


TCL Variable Scope and the upvar Command
• We have already seen that TCL procedures can generate a return
value to pass information back to their caller.
• And, we have also seen that global variables can be used to share
information between parts of a TCL script, and so these also serve as
a mechanism for returning information to a caller.
• TCL includes the "upvar" command as a method for a given
procedure to change the values of variables in the scope of its caller.
This provides a way for a procedure to provide additional information
to the caller, besides by using the procedure's return value.

BVRIT HYDERABAD College of Engineering for Women


• In the "upvar" scheme, a procedure's caller provides the names of one or
more of its own variables as arguments to the procedure.
• The procedure then uses the "upvar" command to map these variables
from the caller onto variables in the procedure.
• For example, here the caller passes its variable name "count" as the first
argument to procedure "getNAvg":
set count 0
set a [getNAvg count "1.0 2.0 3.0 4.0"]
• Then, in this version of procedure "getNArg" the "upvar" command is used
to map the first argument value "$nPtr" onto the procedure's variable
called "n" … this means that whenever the procedure gets or changes the
value of variable "n" it will be using the caller's variable "count".

BVRIT HYDERABAD College of Engineering for Women


Control Flow

• In Tcl language there are several commands that are used to alter the
flow of a program.
• When a program is run, its commands are executed from the top of
the source file to the bottom. One by one. This flow can be altered by
specific commands.
• Commands can be executed multiple times. Some commands are
conditional. They are executed only if a specific condition is met.

BVRIT HYDERABAD College of Engineering for Women


The if command
• The if command has the following general form:
if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?
• The if command is used to check if an expression is true. If it is true, a
body of command(s) is then executed. The body is enclosed by curly
brackets.
• The if command evaluates an expression. The expression must return
a boolean value. In Tcl, 1, yes, true mean true and 0, no, false mean
false.

BVRIT HYDERABAD College of Engineering for Women


!/usr/bin/tclsh
if yes {
puts "This message is always shown”.
}
• In the above example, the body enclosed by { } characters is always
executed.
#!/usr/bin/tclsh
if true then {
puts "This message is always shown”.
}
• The then command is optional. We can use it if we think, it will make
the code clearer.

BVRIT HYDERABAD College of Engineering for Women


• We can use the else command to create a simple branch. If the
expression inside the square brackets following the if command
evaluates to false, the command following the else command is
automatically executed.
#!/usr/bin/tclsh
set sex female
if {$sex == "male"}
{
puts "It is a boy"
} else
{
puts "It is a girl”.
}

BVRIT HYDERABAD College of Engineering for Women


• We have a sex variable. It has "female" string. The Boolean
expression evaluates to false, and we get "It is a girl" in the console.
$ ./girlboy.tcl
It is a girl.

• We can create multiple branches using the elseif command. The


elseif command tests for another condition, if and only if the
previous condition was not met. Note that we can use multiple
elseif commands in our tests.

BVRIT HYDERABAD College of Engineering for Women


Switch command
• The switch command matches its string argument against each of
the pattern arguments in order. As soon as it finds a pattern that
matches the string it evaluates the following body argument by
passing it recursively to the Tcl interpreter and returns the result of
that evaluation. If the last pattern argument is default, then it
matches anything. If no pattern argument matches string and no
default is given, then the switch command returns an empty string.

BVRIT HYDERABAD College of Engineering for Women


#!/usr/bin/tclsh
# switch_cmd.tcl
puts -nonewline "Select a top level domain name:" In our script, we prompt
flush stdout for a domain name. There
gets stdin domain are several options. If the
switch $domain value equals for example to
{
us the "United States"
us { puts "United States" }
string is printed to the
de { puts Germany }
console. If the value does
sk { puts Slovakia }
not match to any given
hu { puts Hungary }
value, the default body is
default { puts "unknown" }
executed, and unknown is
}
printed to the console.
BVRIT HYDERABAD College of Engineering for Women
While command:
• The while command is a control #!/usr/bin/tclsh
flow command that allows code to # whileloop.tcl
be executed repeatedly based on a set i 0
given Boolean condition.
set sum 0
• The while command executes the
while { $i < 10 }
commands inside the block
enclosed by curly brackets. {
incr i
• The commands are executed each
time the expression is evaluated to incr sum $i
true. }
puts $sum

BVRIT HYDERABAD College of Engineering for Women


• In the code example, we calculate the sum of values from a range of
numbers. The while loop has three parts: initialization, testing, and
updating. Each execution of the command is called a cycle.
set i 0
• We initiate the i variable. It is used as a counter.
while { $i < 10 }
{
...
}
• The expression inside the curly brackets following the while command is the
second phase, the testing. The commands in the body are executed, until
the expression is evaluated to false.
incr i
• The last, third phase of the while loop is the updating. The counter is
incremented. Note that improper handling of the while loops may lead to
endless cycles.

BVRIT HYDERABAD College of Engineering for Women


FOR command:
• When the number of cycles is known before the loop is initiated, we can
use the for command. In this construct we declare a counter variable,
which is automatically increased or decreased in value during each
repetition of the loop.
#!/usr/bin/tclsh
for {set i 0} {$i < 10} {incr i}
{
puts $i
}

BVRIT HYDERABAD College of Engineering for Women


• In this example, we print numbers 0..9 to the console.
for {set i 0} {$i < 10} {incr i}
{
puts $i
}
• There are three phases. First, we initiate the counter i to zero. This
phase is done only once.
• Next comes the condition. If the condition is met, the command inside
the for block is executed. Then comes the third phase; the counter is
increased. Now we repeat phases 2 and 3 until the condition is not met
and the for loop is left. In our case, when the counter i is equal to 10,
the for loop stops executing.

BVRIT HYDERABAD College of Engineering for Women


$ ./forloop.tcl
0
1
2
3
4
5
6
7
8
9
Here we see the output of the forloop.tcl script.

BVRIT HYDERABAD College of Engineering for Women


The foreach command:
• The foreach command simplifies traversing over collections of data. It
has no explicit counter. It goes through a list element by element and
the current value is copied to a variable defined in the construct.
#!/usr/bin/tclsh
set planets { Mercury Venus Earth Mars Jupiter Saturn Uranus
Neptune }
foreach planet $planets • In this example, we use the foreach
{ command to go through a list of planets.
puts $planet foreach planet $planets
} {
puts $planet
}
BVRIT HYDERABAD College of Engineering for Women
• The usage of the foreach command is straightforward. The planets is the
list that we iterate through. The planet is the temporary variable that
has the current value from the list. The foreach command goes through
all the planets and prints them to the console.
$ ./planets.tcl
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune

BVRIT HYDERABAD College of Engineering for Women


• Running the above Tcl script gives this output.
#!/usr/bin/tclsh
set actresses { Rachel Weiss Scarlett Johansson Jessica Alba Marion
Cotillard Jennifer Connelly}
foreach {first second} $actresses
{
puts "$first $second"
}
• In this script, we iterate througn pairs of values of a list.
foreach {first second} $actresses
{
puts "$first $second"
}
BVRIT HYDERABAD College of Engineering for Women
• We pick two values from the list at each iteration.
$ ./actresses.tcl
Rachel Weiss
Scarlett Johansson
Jessica Alba
Marion Cotillard
Jennifer Connelly
This is the output of actresses tcl script

BVRIT HYDERABAD College of Engineering for Women


#!/usr/bin/tclsh
foreach i { one two three } item {car coins rocks}
{
puts "$i $item"
}
• We can iterate over two lists in parallel.
$ ./parallel.tcl
one car
two coins
three rocks
This is the output of the parallel.tcl script.

BVRIT HYDERABAD College of Engineering for Women


The break and continue commands:
• The break command can be used to terminate a block defined by while, for, or switch
commands.
#!/usr/bin/tclsh
while true
{
set r [expr 1 + round(rand()*30)]
puts -nonewline "$r "
if {$r == 22} { break }
}
puts ""
• We define an endless while loop. We use the break command to get out of this loop. We
choose a random value from 1 to 30 and print it. If the value equals to 22, we finish the
endless while loop.
set r [expr 1 + round(rand()*30)]

BVRIT HYDERABAD College of Engineering for Women


• Here we calculate a random number between 1..30. The rand() is a
built-in Tcl procedure. It returns a random number from 0 to
0.99999. The rand()*30 returns a random number between 0 to
29.99999.
• The round() procedure rounds the final number.$
./breakcommand.tcl 28 20 8 8 12 22 .We might get something like
this.
• The continue command is used to skip a part of the loop and
continue with the next iteration of the loop. It can be used in
combination with for and while commands.

BVRIT HYDERABAD College of Engineering for Women


• In the following example, we will print a list of numbers that cannot be
divided by 2 without a remainder.
#!/usr/bin/tclsh
set num 0
while { $num < 100 }
{
incr num
if {$num % 2 == 0} { continue }
puts "$num "
}
puts ""
BVRIT HYDERABAD College of Engineering for Women
• We iterate through numbers 1..99 with the while loop.
if {$num % 2 == 0} { continue }

• If the expression num % 2 returns 0, the number in question can be


divided by 2. The continue command is executed and the rest of the
cycle is skipped. In our case, the last command of the loop is skipped,
and the number is not printed to the console. The next iteration is
started.

BVRIT HYDERABAD College of Engineering for Women


Data Structures
• The list is the basic Tcl data structure.
• A list is simply an ordered collection of stuff; numbers, words, strings,
or other lists.
• Even commands in Tcl are just lists in which the first list entry is the
name of a proc, and subsequent members of the list are the
arguments to the proc.
• Lists can be created in several way by setting a variable to be a list of
values set lst {{item 1} {item 2} {item 3}} with the split command set
lst [split "item 1.item 2.item 3" "."] with the list command. set lst [list
"item 1" "item 2" "item 3"]
• An individual list member can be accessed with the index command.

BVRIT HYDERABAD College of Engineering for Women


• The brief description of these commands is
list ?arg1? ?arg2? ... ?argN?
makes a list of the arguments
split string ?splitChars?
• Splits the string into a list of items wherever the splitChars occur in the
code. SplitChars defaults to being whitespace. Note that if there are
two or more splitChars then each one will be used individually to split
the string. In other words: split "1234567" "36" would return the
following list: {12 45 7}.lindex list index
Returns the index'th item from the list.

BVRIT HYDERABAD College of Engineering for Women


• Note: lists start from 0, not 1, so the first item is at index 0, the
second item is at index 1, and so on.llength list.
• Returns the number of elements in a list.The items in list can be
iterated through using the foreach command.foreach varname list
body The foreach command will execute the body code one time for
each list item in list.
• On each pass, varname will contain the value of the next list item.In
reality, the above form of foreach is the simple form, but the
command is quite powerful. It will allow you to take more than one
variable at a time from the list: foreach {a b} $listofpairs { ... }. You can
even take a variable at a time from multiple lists!
• For xample: foreach a $listOfA b $listOfB { ... }

BVRIT HYDERABAD College of Engineering for Women


• Examples
set x "a b c"
puts "Item at index 2 of the list {$x} is: [lindex $x 2]\n"
set y [split 7/4/1776 "/"]
puts "We celebrate on the [lindex $y 1]'th day of the [lindex $y 0]'th month\n"
set z [list puts "arg 2 is $y" ]
puts "A command resembles: $z\n"
set i 0
foreach j $x
{
puts "$j is item number $i in list x"
incr i
}

BVRIT HYDERABAD College of Engineering for Women


Adding and deleting members of a list
• The commands for adding and deleting list members are
concat ?arg1 arg2 ... argn?
• Concatenates the args into a single list. It also eliminates leading and
trailing spaces in the args and adds a single separator space between
args.
• The argsto concat may be either individual elements, or lists. If an arg is
already a list, the contents of that list is concatenated with the other
args.
lappend list Name ?arg1 arg2 ... argn?
• Appends the args to the list listName treating each arg as a list element.

BVRIT HYDERABAD College of Engineering for Women


linsert list Name index arg1 ?arg2 ... argn?
• Returns a new list with the new list elements inserted just before the
index th element of listName.
• Each element argument will become a separate element of the new
list.
• If index is less than or equal to zero, then the new elements are
inserted at the beginning of the list. If index has the value end, or if it
is greater than or equal to the number of elements in the list, then
the new elements are appended to the list.

BVRIT HYDERABAD College of Engineering for Women


lreplace list Name first last ?arg1 ... argn?
• Returns a new list with N elements of listName replaced by the args. If
first is less than or equal to 0, lreplace starts replacing from the first
element of the list.
• If first is greater than the end of the list, or the word end, then lreplace
behaves like lappend. If there are fewer args than the number of
positions between first and last, then the positions for which there are
no args are deleted.

BVRIT HYDERABAD College of Engineering for Women


lset varName index newValue
• The lset command can be used to set elements of a list directly,
instead of using lreplace.
• Lists in Tcl are the right data structure to use when you have an
arbitrary number of things, and you'd like to access them according to
their order in the list. In C, you would use an array.
• In Tcl, arrays are associated arrays - hash tables, as you'll see in the
coming sections. If you want to have a collection of things and refer to
the Nth thing (give me the 10th element in this group of numbers) or
go through them in order via foreach.

BVRIT HYDERABAD College of Engineering for Women


• Look at the example code and pay special attention to the way that
sets of characters are grouped into single list elements.
Example
set b [list a b {c d e} {f {g h}}]
puts "Treated as a list: $b\n"
set b [split "a b {c d e} {f {g h}}"] # Note: {ij K lm} is a single element
puts "Transformed by split: $b\n" puts "After lappending: $a\n"
set a [concat a b {c d e} {f {g h}}] set b [linsert $a 3 "1 2 3"] ;
# "1 2 3" is a single element
puts "Concated: $a\n"
puts "After linsert at position 3: $b\n"
lappend a {ij K lm} ; set b [lreplace $b 3 5 "AA" "BB"]
puts "After lreplacing 3 positions with 2
values at position 3: $b\n"
BVRIT HYDERABAD College of Engineering for Women
More list commands - lsearch, lsort, lrange
• Lists can be searched with the lsearch command, sorted with the lsort
command, and a range of list entries can be extracted with the lrange
command.
lsearch list pattern
• Searches list for an entry that matches pattern, and returns the index
for the first match, or a -1 if there is no match. By default, lsearch uses
"glob" patterns for matching. See the section on globbing.
lsort list
• Sorts list and returns a new list in the sorted order. By default, it sorts
the list into alphabetic order. Note that this command returns the
sorted list as a result, instead of sorting the list in place. If you have a
list in a variable, the way to sort it is like so: set lst [lsort $lst]
BVRIT HYDERABAD College of Engineering for Women
lrange list first last
• Returns a list composed of the first through last entries in the list. If
first is less than or equal to 0, it is treated as the first list element. If
last is end or a value greater than the number of elements in the list,
it is treated as the end. If first is greater than last then an empty list is
returned.
• Example
set list [list {Washington 1789} {Adams 1797} {Jefferson 1801} \
{Madison 1809} {Monroe 1817} {Adams 1825} ]
set x [lsearch $list Washington*]
set y [lsearch $list Madison*]
incr x

BVRIT HYDERABAD College of Engineering for Women


incr y -1 ;# Set range to be not-inclusive
set subsetlist [lrange $list $x $y]
puts "The following presidents served between Washington and Madison"
foreach item $subsetlist {
puts "Starting in [lindex $item 1]: President [lindex $item 0] "
}
set x [lsearch $list Madison*]
set srtlist [lsort $list]
set y [lsearch $srtlist Madison*]
puts "\n$x Presidents came before Madison chronologically"
puts "$y Presidents came before Madison alphabetically"

BVRIT HYDERABAD College of Engineering for Women


Input / Output
• Tcl uses objects called channels to read and write data.
• The channels can be created using the open or socket command.
• There are three standard channels available to Tcl scripts without explicitly
creating them.
• They are automatically opened by the OS for each new application. They
are stdin, stdout and stderr.
• The standard input, stdin, is used by the scripts to read data.
• The standard output, stdout, is used by scripts to write data.
• The standard error, stderr, is used by scripts to write error messages.
• In the first example, we will work with the puts command. It has the
following synopsis:

BVRIT HYDERABAD College of Engineering for Women


• The channelId is the channel where we want to write text. The
channelId is optional. If not specified, the default stdout is assumed.

puts ?-nonewline? ?channelId? string

puts "Message 1"


puts stdout "Message 2"
puts stderr "Message 3"
• The puts command writes text to the channel.
puts "Message 1"
puts stdout "Message 2"
puts stderr "Message 3"
BVRIT HYDERABAD College of Engineering for Women
• If we do not specify the channelId, we write to stdout by
default. This line does the same thing as the previous one. We
only have explicitly specified the channelId.
• We write to the standard error channel. The error messages go
to the terminal by default.

BVRIT HYDERABAD College of Engineering for Women


The gets command.
• The gets command reads the next line from the channel, returns everything
in the line up to (but not including) the end-of-line character.
#!/usr/bin/tclsh
puts -nonewline "Enter your name: "
flush stdout
set name [gets stdin]
puts "Hello $name"
• The script asks for input from the user and then prints a message. The puts
command is used to print messages to the terminal. The -no newline option
suppresses the new line character.
• Tcl buffers output internally, so characters written with puts may not
appear immediately on the output file or device. The flush command forces
the output to appear immediately.
BVRIT HYDERABAD College of Engineering for Women
The pwd and cd commands
• Tcl has pwd and cd commands, like shell commands. The pwd command
returns the current working directory and the cd command is used to
change the working directory.
#!/usr/bin/tclsh
set dir [pwd]
puts $dir
cd ..
set dir [pwd]
puts $dir
• In this script, we will print the current working directory. Then we
change the working directory and print the working directory again.

BVRIT HYDERABAD College of Engineering for Women


set dir [pwd]
• The pwd command returns the current working directory.
cd ..
• We change the working directory to the parent of the current directory.
We use the cd command.
$ ./cwd.tcl
/home/janbodnar/prog/tcl/io
/home/janbodnar/prog/tcl
Sample output.

BVRIT HYDERABAD College of Engineering for Women


The glob command
• glob provides access to the names of files in a directory. It uses a
name-matching mechanism similar to the UNIX ls command or the
Windows (DOS) dir command, to return a list of names that match a
pattern.

#!/usr/bin/tclsh
set files [glob *.tcl]
foreach file $files
{
puts $file
}
• The script prints all files with the .tcl extension to the console. The glob
command returns a list of files that match the *.tcl pattern.
BVRIT HYDERABAD College of Engineering for Women
We go through the list of files and print each item
set files [glob *.tcl] of the list to the console.
foreach file $files $ ./globcmd.tcl
{ attributes.tcl
allfiles.tcl
puts $file printing.tcl
} hello.tcl
read.tcl
files.tcl
globcmd.tcl
write2file.tcl
cwd.tcl
readfile.tcl
isfile.tcl
addnumbers.tcl
This is a sample output of the globcmd.tcl script

BVRIT HYDERABAD College of Engineering for Women


Procedures
• A procedure is a code block containing a series of commands.
Procedures are called functions in many programming languages.
• It is a good programming practice for procedures to do only one
specific task.
• Procedures bring modularity to programs. The proper use of
procedures brings the following advantages
1. Reducing duplication of code
2. Decomposing complex problems into simpler pieces
3. Improving clarity of the code
4. Reuse of code
5. Information hiding

BVRIT HYDERABAD College of Engineering for Women


• There are two basic types of procedures: built-in procedures and user
defined ones.
• The builtin procedures are part of the Tcl core language. For instance,
the rand(), sin() and exp() are built-in procedures.
• The user defined procedures are procedures created with the proc
keyword.The proc keyword is used to create new Tcl commands.
• The term procedures and commands are often used interchangeably.
We start with a simple example.
#!/usr/bin/tclsh
proc tclver {}
{
set v [info tclversion] In this script, we create a simple tclver
procedure. The procedure prints the
puts "This is Tcl version $v“ version of Tcl language. proc tclver {}
}
BVRIT HYDERABAD College of Engineering for Women
• The new procedure is created with the proc command. The {} characters reveal that the
procedure takes no arguments.

proc tclver {}
{
set v [info tclversion]
puts "This is Tcl version $v"
}
tclver
• This is the body of the tclver procedure. It is executed when we execute the tclver
command. The body of the command lies between the curly brackets.The procedure is
called by specifying its name.

This is Tcl version 8.6


Sample output.

BVRIT HYDERABAD College of Engineering for Women


Procedure arguments:
• An argument is a value passed to the procedure. Procedures can take
one or more arguments. If procedures work with data, we must pass
the data to the procedures.
• In the following example, we have a procedure which takes one
argument.
#!/usr/bin/tclsh
proc ftc {f}
{
return [expr $f * 9 / 5 + 32]
}
puts [ftc 100]
puts [ftc 0]
puts [ftc 30]
BVRIT HYDERABAD College of Engineering for Women
• Output of the example.
$ ./fahrenheit.tcl
212
32
86

BVRIT HYDERABAD College of Engineering for Women


Recursion
• Recursion, in mathematics and computer science, is a way of defining
functions in which the function being defined is applied within its own
definition.
• In other words, a recursive function calls itself to do its job. Recursion is
a widely used approach to solve many programming tasks.
• Recursion is the fundamental approach in functional languages like
Scheme, OCalm, or Clojure.
• Recursion calls have a limit in Tcl. There cannot be more than 1000
recursion calls.
• A typical example of recursion is the calculation of a factorial. Factorial
n! is the product of all positive integers less than or equal to n.

BVRIT HYDERABAD College of Engineering for Women


Scope
• A variable declared inside a procedure has a procedure scope.
• The scope of a name is the region of a program text within which it is
possible to refer to the entity declared by the name without
qualification of the name.
• A variable which is declared inside a procedure has a procedure
scope; it is also called a local scope. The variable is then valid only in
this procedure.

BVRIT HYDERABAD College of Engineering for Women


strings
• Many operations on strings in Tcl are carried out by the generic string
command. The first argument to string defines the operation to be
performed, the second is the string to be operated on, and there are
additional arguments for some operations.
• Characters in a string are indexed from zero: the special keyword end can
be used to refer to the last character in a string.
• The most useful operations are as follows.
❑ string compare lexicographic comparison.
string compare $81 $82
• returns 0 if strings 81 and 82 are identical, -1 if 81 sorts lexicographically
before 82, and +1 if 81 sorts after 82.

BVRIT HYDERABAD College of Engineering for Women


• Always use this method to order strings do not be tempted to use the
arithmetic comparison operators ! =, >, > =, < and < =).
• Although these operators will often work, provided that you
remember to put the string in quotes and then enclose the whole
expression in braces to stop the parser stripping off the quotes,
mysterious things can happen.
❑ string match pattern matching.
❑ string trim, string trimleft, string trimright useful for tidying up
strings. For example
string trim $8
• will remove leading and trailing whitespace characters from string 8.
string trimleft and string trimright have obvious meanings. Other
characters can be trimmed by providing a further argument.
BVRIT HYDERABAD College of Engineering for Women
• Thus string
trimright $8 0123456789
will trim trailing digits from string 8.

❑ string tolower, string toupper case conversion.


• Note also that although commands like string range, string wordstart
and string wordend provide the ability to decompose strings in
various ways.

BVRIT HYDERABAD College of Engineering for Women


Other string operations
Other string commands include append, format, split and subst.
• append takes a variable name as its first argument and concatenates the remaining
arguments onto the end of the current value of the variable, e.g.
set message {Hello World}
append $message ", have a nice day\n"
• format formats a string in the same way that C printf function does: if a has the value
1234567.89,
puts [format "%10.2f %10.8e" $a Sa)
prints the value of a in decimal form (total width of 10 characters with two digits after
the decimal point) and in scientific notation (mantissa compromising 10 characters with
8 digit after the decimal point plus exponent), thus:
1234567.89 1.2345678ge+06

BVRIT HYDERABAD College of Engineering for Women


Working with patterns
• TCL provides two varieties of pattern matching, the so-called 'glob matching',
which is a simple wild card technique and more sophisticated regular
expression matching.

Glob matching
• Simple pattern matching using is accomplished by string match.
• This performs glob matching using just three patterns: * matches any number
of characters ? matches a single character and [abc] matches any one of the
set of characters enclosed in the brackets.
• (Remember that if you use a choice-of-alternatives pattern it must be hidden
within braces or stored as the value of a variable, otherwise the interpreter
will try to do a command substitution.)
• Thus string match {[A-z] [a-z]*} $name will return true if the value of $name is
a string of alphabetic characters with the first character capitalized.

BVRIT HYDERABAD College of Engineering for Women


Regular expression matching
• More complex matching using regular expressions is done using the
regexp command,
e.g. regexp {[a-zA-Z]*} $foo
regexp {[a-zA-Z]*} $foo bar
• In these examples, the pattern is a regular expression that matches any
sequence of upper- or lower-case letters
• In both cases the command returns 1 if a match is found in the value of
the variable f00: in the second case, as well as returning a value, the
string that was recognized by the match will be stored in the variable
bar.

BVRIT HYDERABAD College of Engineering for Women


regexp optionalSwitches patterns searchString fullMatch subMatch1 ...
subMatchn
files and pipes
Associating a stream with a file or pipe
• So far we have encountered the predefined streams stdin, stdout and stderr for
input and output.
• A stream is associated with a file by the open command, e.g.
set myfile [open /tmp/foo w 0600]
puts $myfile "This goes to foo"
• (The name assigned to a stream is also referred to as a 'file descriptor'.) The
mode and permissions arguments are optional. The mode determines how the
file can be accessed, the default being read only. The permissions determine
who can access the file and are expressed in the standard UNIX format: the
default is 0666.
• (Note that the use of permissions in this style in non-UNIX implementations of
Tel mayor may not work, depending on the capabilities of the underlyning
operating system: consult the local manual.)
BVRIT HYDERABAD College of Engineering for Women
open fileName accessMode

close fileName

set fp [open "input.txt" w+]


puts $fp "test"
Writing a File close $fp
set fp [open "input.txt" w+]
puts $fp "test"
close $fp
set fp [open "input.txt" r]
set file_data [read $fp]
Reading a File puts $file_data
set file_data [read $fp] close $fp
Thank You

You might also like