0% found this document useful (0 votes)
69 views42 pages

Scripting Languages U-5

The document provides an overview of TCL (Tool Command Language) and Tk, detailing their structures, syntax, and various commands. It outlines the learning objectives, features, and benefits of TCL, emphasizing its usability in application development and its integration with Tk for graphical user interfaces. Additionally, it covers advanced concepts such as error trapping, namespaces, and event handling in TCL programming.

Uploaded by

csecmailid
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)
69 views42 pages

Scripting Languages U-5

The document provides an overview of TCL (Tool Command Language) and Tk, detailing their structures, syntax, and various commands. It outlines the learning objectives, features, and benefits of TCL, emphasizing its usability in application development and its integration with Tk for graphical user interfaces. Additionally, it covers advanced concepts such as error trapping, namespaces, and event handling in TCL programming.

Uploaded by

csecmailid
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/ 42

L o go

onthe
Titlo
Covo

UNIT befor
SIA GROUP
TCL and Tk
SIA GROUP

Syllabus
TCL: TCL Structure, Syntax, Variables and Data in TCL Control Elew Dsta Structures, Input/Output, Proceure
Patterns, Files, Advance TCL- eva, source, exec and uplevel Commands, Name Spaces, Trapping Errors, EYen
Programs, Making Applications Internet Aware, Nuts ond Bolts nternet Programming, Security lsues, nen
Tk: Tk-Visual Tools Kits, Fundamental Concepts of Tk, Tk by Example, Events and Binding, Perl-Tk.

LEARNING DBJECTIVES

Introduction of TCL, Structure of TCL and its Syntax


Defining Control Flow, Data Structures, Input/Output, Procedures and Files
Advanced TCL - eval, Source, exec and uplevel Commands
Concepts of Namespaces, Trapping Errors and Nuts and Bolts Internet Programming
Tk-visual Tool Kits, FundamentalConcepts of Tk
Concepts of Events and Binding, PerlVersus Tk.

INTRDDUGTION

TCL stands for ToolCommand Language. It is a reusable command language whose procedures are defined
by the users for commands that are very powertul than the commands on the tools. base set, TCL is one of
the best alue langugge. A TCL command is evalvated in two steps i.e., parsing and execution, The three
looping commands provided in TCL are while, tor and for-each. TCL supports different yoarigbles and
evaluates them within its scope. TCL provide two pattern matching techniques. Inorder to intearate TCI
be collèd
into an application, only a TCL header is included and TCL_ Createlnterp must
Visual toolkits has an important role in application programming. The bind command is Used to register a
one or more evente
callback script which has to be executed on fhe occurrence of

cPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS


5.2
SCRIPTING LANGUAGES [JNTU-HYDERABAD]
PART-A SHORT QUESTIONS WITH SOLUTIONS

Q1. Write a short notes on TCL.

Answer :
Ousterhout vf the University of California in late
TCL stands for Tool Conmand Language. It is developed by John K.
1980s. lt was first distributed in 1989,
along with sufficient programming to define procedures to
TCL is a reusable command language. It issues commands
for commands that are very powerful than the commands on
various interactive tools. These procedures are defined by the users
in an application to provide a simple command line interface.
the tools base set. TCL also acts as an interpreter. It is embedded
for developing many applications in National Broadcasting
TCLhas little syntax and no inherent semantics. It is used
Company (NBC), Cisco etc.
Q2. Discuss in brief about if command.
Model Paper-l, Q1(0)
Answer :
result is
If the result is true, the TCL Script is executed. If the
The if command evaluates the expression, tests the results.
false, if returns and no further action is taken. Example,
if{Sr < 0}

set x 0

-}
script, In
is an expression and the second argument is a TCL
The above command has two arguments, the first argument clause with a script
clauses can be included. The final clause will be the else
order to add more scripts to the if command, else if
that has to be evaluated if no other script succeeds.
if{Sx < 0}{

}elseif{$x ==0} {

}elseif{Sx = =1}{

}else{

value ofx. The


The above command has four scripts among which only one script will be executed depending on the
braces
resulting value of the evaluated script willbe the result of the command. Theexpressions and scripts are to be enclosed in
so that they are postponed till the execution of the command.
Q3. Write a short notes on pattern matching using regular expression.
Answer :

Pattern matching technique is very powerful and is used for complex pattern matching. The regular exprcssion matchins
is done using the regexp command.
The syntax of regexp command is,
(a) regexp pattern string
It returns Ion success and 0on failure

(b) regexp pattern string variable.


In this case, apart from return1ng the value Ior 0, the string that matches the pattern is stored in the variable.

WARNING: Xerow/Photocopying of this book is aCRIMINAL, act. Anyone found guity i_ LJABLE to face LEGAL proceedings.
UNIT-5 TCL and Tk 5.3
Q4. Write about eval command.
Answer :

The creation and exeçution ofTCL script is done by the 'eval' command, This 'eval' command takes a number of arguments
and concatenates them using aseparator 'space'. It thencalls the interpreter to execute the output (resulting string) as a TCLscript.
The most common use of eval' is that it allows all the TCL parsing rules to be applied to the script. By this, the script contains
alarge number of commands, comments, multiple lines etc. The commands generated by 'eval' are stored in variables and are
later executed as TCL scripts.
05. Discuss in brief about server sockets.
Answer :
Model Paper-l, Q1(0)

Server socket provides access to multiple connections. When aconnection is established with the well known port, then
anew socket is created and the server listens to the further requests.

Server sockets are well known as listening socket. Server sockets are created by using socket command with server option
as shown below,
socket - server command?options ? port
Inis will establish the server socket on the current host at a given port number. Servername can also be passed instead of
port number depending on the operating system.
Q6. Write a short note on slave interpreter.
Answer :

A slave interpreter is a TCL interpreter that run as a separate process under the control of master interpreter. A slave
interpreter creates anew instance of TCIL interpreter that has its own global and procedure namespace. It does not have privileges
to access the variables or procedures of the master with an exception of sharing only environment variable is used between the
master and the slaye.

Q7. Write a short note on visual toolkits.


Answer : Model Paper-, Q1()
Visual toolkits has an important role in application programming. Implementation of visual interfaces is possible with
library of functions that implement building blocks like menus, buttons, dialog boxes etc. It is dificult to perform low-level
programming of visual interfaces because each and every pixel on the screen has to be defined. The operating system offers an
abstraction at asimple level which is far away from pixels. Even with this simple level abstraction the developer's programming
is at a level which is very low.
Q8. Write about widget name and widget properties.
Answer : Model Paper-ll, Q1(0)
Widget Names
Widget name is the name of the widget that is given soon after its creation. It must be unique among all the other widgets.
It must lie in the same level in the hierarchy.
Widget Properties
Widget properties are set as soon as the widgets are created. The properties signify the appearance of the widgets like its
colour, font size etc. Many widgets have common properties like size, colour, orientation and appearance. The properties can be
changed accordingly. After the creation of a widget, a command with same name is defined instantly for the modification of the
properties later. The instant creation of the command with same name is shown below,
frame.fr-text Go.
e

.frconfigure -text stop

SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS


s
5.4
Q9.
SCRIPTINGLANGUAGES (JNTU-HYDERABAD):
Write short notes on Events.
Answer : Model Paper-ll, Q1()
An event is an action perfornned by the user. In the delegation cvent model, an event is an object that shows a status i.e.,
state changes in a source, Events are generated whenthe user interacts with the clements in agraphical user interface.Some of
selecting an item in alist, clickingthe
the actions thatgenerate events are pressing abutton, entering the data via keyboard,
mouse
etc. These are allthe cvents that are generated bya uer by interacting with a user interiave:
Events nay also be generated without Interacting with user interface. For example, an event may be generated when the
completed.
timer eXpires, a counter reaches a value, a software or hardware failure 0ccurs, or an operation is
Syntax
bind .w <Button -1>{
bind .w <key-space> {-}
Q10. Write about virtual events.
Answer : Model Paper-4, Q10)
A irual event is an event which is associated with multinle event sequences. It fires on the occurence or one of these
Sequences. For example, a virtual paste' event canbe created in awindows application which will ire on crl - VOr shift-insert
Cveut addspaste> <control-key-v>/<shift-key-insert> virtual events use double angle brackets. It can be Used in a bind command
like other events.

Bind entry <<paste>> {%w insert [selection get]}


It can be raised by the event generate command in a script.

WARNING: Xerox/Photocopying of this book is a CRIMINAL.act. Anyone found guilty is LIABLE to face
LEGAL-proceedings.
UNIT-5 TCL and Tk
5.5

PART-B ESSAY QUESTIONS WITH


5. TCL SOLUTIONS
Q11. What is TCL? Explain the benefits of
Answer: TCL.
TCL Model Paper-ill, Q10(a)

rCL stands for Tool


Command
distributed in 1989. Language. is develoned by John K.
1980s. It was first It
Ousterhout of the University of
Caoe
TCL 1s a reusable
rarivus interactive tools. command language. It issues commands along with
These sufficient programming to deie
1ools base set. TCL also acts procedures are defined by the users for
as an interpreter. It is commands p
that are very powerful than the a
commands on
TCL has llttie syntax and no inherent embedded in an application to provide a simple command line interface.
Company (NBC), Csco etc. semantics. It is used -for develoning many applications in
National Broadcasing
Benefits of TCL
TCLproVides several benefits to application
develoners and users, It is beneficial because of the following
1 Rapid Development reasons,
Many applications use TCL scripts as they allow users to
size and development time is reduced to a large program at a much higher level than C, C++ or Java. The script
extent when TCL scripts are used. The
directly without recompiling or restarting the application. Thus, this generated scripts are
Less Learning and User allows users to test new scripts and fix bugsexecutea
rap1dly.
Convenient
To use TCL, users have to learn very less and in hours of
learning thevy can create user interfaces. To develop new
Thus, this makes it convenient to many users toapplications,
the user just needs to learn application specific
and enhance their applications. commands. personalize
3. Interpreted Language
TCL Scripts are interpreted. This feature is very beneficial as it
allows TCL users to try new scripts and fix bugs in the
seripts easily.
4 Cross Platform Language
This feature of TOL is beneficial as it runs an application developed on one
platform in another platform.
Example
An application developed in Linux can be run in Macintosh or Windows without
making any changes.
5 Native Unicode Support
The first dynamic language to support native unicode is TCL. TCL handles text written in any of the
world's written language.
It requires no extensions to process such text. But, a stahdard extension, msgcat is used to support simple
localization.
6
Freely Available
TCL is freely available as open source. It follows BSD license. Thus, any one caD view, download, modify and share TCL
without any permission.
Glue Language
TCL is one ofthe best glue l¡nguage. Various library packages have been developed by TCL. In addition, users can
create
their own packages.
An application using TCL includes many, other TCL extensions. That provide set of TCL commands., That is. these
application can include commands from any of these packages.
8
Produce a Scripting Language
TCL helps to have powerful scripting language in applications that require, it add scripting to an existing application, user
just necds to implement new TCL commands that are suitable to the application. These commands are then linked to the
TCL library. In this way, it provides both TCL commands and new commands written by user. Thus, providing apoweriul
scripting language.
SPECTRUM AL;IN-ONE JOURNAL FOR ENGINEERING STUDENTS
5.6 SCRIPTING LANGUAGES [JNTU-HYDERABAD]
Q12. What are the features of TCL?
Answer :
Features of TCL
The features of TCLare as follows,
1. Operation
language.
It operates on commands which are written in prefix notation. It is called reusable command
2 Easy to Learn
TCL has very simple syntax which is easy to learn.
Flexible
TCL is very flexible and this makes convenient to the users to personalize and enhance their applications.

Interpreted Language
TCL seripts are interpreted. They are executed directly without recompiling or restarting the application.
5. Cross Platform Language
language. Example, a Linux
TCLsupports cross platform i.e., an application developed in one language can run in another
application can run in Windows API, Macintosh etc.
6. Datatype
All the datatypes in TCL are treated as strings.
7 Powerful
commands on the
TCLis a very powerful language. It defines procedures for commands that are very powerful than the
tools base set.
8 Native Unicode Support
TCL Supports native unicode. It handles text written in any of the world's written language.
9. Interface Support
TCL includes event driven interface to sockets and files. It also includes time based events and user-defined events.
10. Freely Available
TCL follows BSD license. It is available as an open source. It can be viewed, downloaded, modified and also be shared.
11. Extended and Embedded

TCL can be extended in many ways in C, C++, Java, TCL itself. It can also be embedded directly into the applications.
12. TK Toolkit

TCL is closely integrated with the TK toolkit which has Graphical User Interface (GUI).
5.1.1TCL Structure
Q13Éxplain the structure of TCL.
Answer :

TCL Structure

The users interact with UNIX shell or DOS using commands. Since, many users are familiar with the command line syntax,
TCL inplements command line syntax.
Acommandconsists of one or more words separated by whitespace. If it contains more than one word then, the first word
is called command word and the remaining words are called arguments. The command word can be a build-in command or a
TCL Drocedure written by user or an external C function supplied by user. The interpreter makes the arguments available to the
command or a procedure or a function by passing control on them. Since, the TCL has no inherent semantics, the semantics 15
already available in the code that is associated with command word (i.e., first word).

WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
UNIT-5 TCL and Tk
5.7
TCL is embedded in host applications toprovide a simple
snd the TCL interpreter is shown in the figure below. command line interface. The interaction between the application

lHost application TCL interpreter

User User
input interface Parser

C library Build- in TCL


functions commands procedure

Figure (1): Interaction Between Host Application and TCL


Interpreter
The application passes the user input to th¿TCL parser. The parser
then identifies the command word by breaking input
intowords. Finally, the control is passed to the built-in commands, TCL
structure of TCL. procedures and Clibrary functions. This is a 'classic"
Now a days, many applications are build using TCL. In such case, the application
shell as shown in the figure (2). shown in figure (1) simply becomes a

Shell (tclsh) TCL interpreter

Read from
Parser
keyboard
or file

Build-in TCL
commands procedure

Figure (2): TCL Structure


The input is read from the keyboard or file. The shell then passes the input to the TCL parses. One such shellwhich is a
part of TCL is tclsh.

5.1.2 Syntax
Q44. Describe the syntax of TCL.
Answer :
TCL Syntax
ATCL command consists of one or more words separated by white space. The first word in the TCL Command is cálled
command word and the remaining words are called arguments. The syntax is as follows:
cmd arg arg arg
A word isa sequence of characters without any spaces or a tab. A word can have a dollar sign ($) or a backslash (\).
Dollar sign substitutes the value of a variable. It is also called substitution operator.
Example: Mr. Sname
Here, the $ is used to substitute the value of the variable 'name'.
Backslash is used to introduce spècial characters.
Example: \n introduces new line
Backslash is also used to disable the special meaning of dollar sign, quotes, square brackets and curly brackets.
Example: Friend\$ is for Friend$
To execute a nested command, we use square brackets. In this case, the output of one command is passed as an argument
b another command.

Example: [clock seconds]


This gives the current time in seconds.
SPECTRUM ALL-HN-ONE JOURNAL FOR ENGINEERING STUDENTS
SCRIPTINGLANGUAGES rJNTU-HYDERABAD)
5.8
90
set
To group words separated by spaces together, we can 2.
Set
20
enclose them in double quotes or curly braces. If' we enclose Sa * $h
CXpr
them in double quotes, it interrupts the dollar sign and square
brackets inside it. Output
Ex:ample:"Good moming Snane" I800
In this example, the first two commands set a and h
Here, Sname is substituted by its value, If we enclose command multiplies both
values. The third of
them in curly braces, it interrupt the dollar sign and square
brackets inside it.
variable substitution. them by
Exaruple: (Weleome SIA Publication} ${variablename}
3
The variable name
can be enclosed with
is replaced by{}.In this
Here, SlA Publication remains unchanged.
Q15. Define word. Explain three forms of substitutions. example, ${variablename}
notation value of
{variablename}. This is generally used
Answer :
unusual variable name
such as *9* with
Word Command Substitution
(ii)
Aword is a set of characters i.e., a string. It is bounded This type of substitution takes place when word is
by start or awhite space on the left and a command terminator brackets. The TCLinterpreter isso
enclosed between square called
ora white space on the right considering the following cases, between the square brackets.
recursively
text
to processthe text
must be a valid TCL script. Thesquare bracket and thetexThe
Case 1
betweenthem is replaced by the resulttof the script. The backtick
If the word starts with an opening brace (), then it command substitution
should be terminated by the matching closing brace (}). The and gx operators in Perlhelp in
text inbetween these brackets is not processed. Example
Case 2 set a 20
If the word starts with an opening square bracket (), then set 30
it should be terminated by the matching square bracket (). The set result [expr Sa*$b]
text in between these square brackets is processed.
Case 3
Output
result =600
If the word starts with a double quote, then it should be
In this example, the third command sets the yalue of
terminated by the next double quote. One or more substitutions result. Firstly, the expression inside the square brackets is
are done to the text between these quotes while the semicolon,
backsiash, white spaces are treated as ordinary characters. evaluated and then the result is passed as argument. It becomes
as follows,
When the parser scans the word from left to right, there.
set results 600
is a possibility of substituting text other than the text enclosed
in matching braces. Some of thesubstitutions provided by TCL (ii) Backslash Substitution
are, This type of substitution takes place when the word
(i) Variable substitution contains backslash (). It is used to introduce special characters.
(ii) Command substitution To use dollar sign in a string it must be appended by abackslash
as \S. Similarly, to use backslash in a'string it should be written
(iii). Backslash substitution. as \\.
(i) Variable Substitution The table below lists the backslash substitutions
This type of substitution takes place when a word supported by TCL.
contains a dollar sign (S). The value of the variable is inserted
at the place of the word that is followed by dollar sign. Let us Character Special Meaning
see some of the examples. Backspace
Examples Alert
40 \f Form feed
set
Sa*2
Newline
expr
Carriage return
Output It Tab
Vertical tab
In this cxample, the first command sets the value 40 to Aodd Character with octal code dd
the variable a. The second command doubles the value
\xhh Character with hex code hh
ofa. This is done by variable substitution. The string Sa
is replaced by 40 and then is multiplied by 2 as 40*2, Table: Backslash Substitutions
WARNING: Xerox/Photocopying of this book IS a GRIMINAL act. Anyone found guilty is LIABLEto face LEGAL proceedings.
5.9
UNIT-5 TCL and Tk
Let us see few examples where the meaning of the
Example arguments is not bothered by the TCL interpreter.
set price \S10
set Bookdetails Scripting languagesln cost:$price (i) set X 40

Output set 40 X

Scripting languages The syntax of 'sct'command is set variable name value


Cost:$10 i.e., first argument is variable name and second argument
o16. Explain the process of parsing and executing is value. The above two commands are valid. The first
TCL commands. command assigns 40 to xi.e, x = 40 while the second
Answer : command assigns x to 40 i.e., 40 =x.
£valuating a Command expr 34/4.1
(ii)
A TCL command is evaluated in two steps. They are
arsing and execution. The expr command results in an arithmetic expression
Atep 1: Parsing after concatenating its arguments. Many other commands
take expressions as arguments.
In this step, the TCL interpreter divides the command
ato words based on some rules. The parser then performs (ii) Lindex{JNTUA JNTUHJNTUK} 1
abstitutions on the words wherever necessary. This step is
peated in the same way for all the commands. The syntax of index command is,
itep 2: Execution lindex list index
In this step, the first word is treated as command name The list is {JNTUA JNTUH INTUK}. It has thre
nd the remaining are treated as arguments. TCL then checks elements separated by spaces. The index is 1 which
fthe command isdefined and locates the còmmand procedure means the element at index 1has to be returned (i.e.,
Dcarryout its function. TCL interpreter invokes the command
JNTUH has to be returned as index start from 0).
r0cedure if the command is defined and passes all the words
pit. The command procedure assigns different meaning to Q7. Define TCL structure. Give a brief note on
ifferent words i.e., different meaning to different command
names and different arguments. . examples of parsing.
The figure below describes the process of parsing and Answer : Dec.-14(RO9), Q5(a)
execution for evaluating a TCL command. TCL Structure
String match "*and the*" $input Commånd
For answer refer Unit-V, Q13.
string
Examples of Parsing
Parser TCL parser
For answer refer Unit-V, Q16.
Pafsing
String Command name 5.1.3 Variables and Data in TCL
Q18. What is the internal storage of data in TOCL?
Match
Arguments Explain the usage of "set" and expr" command
*are the with suitable examples.
India is the Best Answer :
Exècution Call to command Internal Storage of Data in TCL
Command procedure (string) procedure
Alltypes of data such as integers, real numbers, names,
Resut lists and TCL scripts are represented internally only in the form
(Not successful)
of strings in TCL. It has only one datatype i.e., string and only
Figure: Evaluating TCL Command by Parsing and Execution one data structure i.e., an array. Strings make the communication
In this figure, the TCLparser divides the given command simple between sçripts and command procedure. Initially, TCL
o words. The parser then substitutes Sinput with its value. stores only string representations. The received words are
'hile substituting, the TCL interpreter does not bother about interpreted and converted into appropriate TCL variables by the
emeaning of the values of the variables that are substituted. command procedure. The expr command is used for evaluation
ust replaces the variable with its value. It does not bother if of expressions. It recognizes the strings and converts them into
ia number or name or anything else. following appropriate TCL variables,
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SCRIPTING LANGUAGES rJNTU-HYDERABAD
5.10
The above command has two arguments,
1. String that represent numbers are
converted into
argument is an expression and the second argument
is a
the first
2.
numbers.
String of decimal digits is treated as decimal integer until
script. In order to add more
clauses can be included. The
scripts to the if
command, elTCL
final clause will be the se if
it does not start with zero. In this caSC, evaluated ifno else
other scrnpt clause
with a script that has to be
(i) The string is treatcd as an octal, if'the next
character
ir(Sr < 0){
succeeds.
is a digit.
the
(11) The string is treated as hexadecimal number, if
string starts with 0X.
}elseif(Sx==0}{
(iii) All other numbers including decimal point and
scientific notation are converted into floating point.
3. A number is required in case of Boolean value such as }elseif{Sx ==1}
zero is treated as false and others are treated as true.
Since, all the values appear to be strings, the TCL
interpreter manages memory allocation for values and
improves its performance by converting string and internal
representations. }else{
set Command
set is a built-in command that is used for assignment.
Example
set a 6; The above command has four scripts among which only
one script will be executed depending on the value of x. The
set b "web programmingin"; resulting value of the evaluated script will be the result of the
Only two words are to be given for set command or else command. The expressions and scripts are to be enclosed in braces
it complains if more or less than two words are found. The first so that they are postponed till the execution of the command
character after set represents the variable name and the second
character represents the value to be assigned. Switch Command
expr Command
Like if command, having number of else if clauses, the
The expr is a built-in command that is used for evaluating 'switch command also has number of patterns. Avalue is tested
the expression.
against these patterns and the script of the matching pattern is
Example executed. The switch command can be expressed in two forms,
expr Sa *(SC + 4)2) but only one of the form is preferred mostly.
In the above expression, the expr command first Switch Sa
concatenates all the arguments into asingle string by performing
variable and command substitution. x {incr t1}
expr {Sa *($C + 4)/2)} y {incr t2}
After concatenation, the string is evaluated by
recognizing brackets and applying operator precedence rules. z {incr t3}
5.1.4 Control Flow
Q15. Explain the "if" and "switch" commands. The above given form of a switch command is mostly
preferred because the patterns and scripts can be spread across
Answer :
multiple lines. The above command has two arguments, the nTSt
if Command argument denotes the value to be tested against the pattems,
the second argument is a list of one or more pairs of elements.
The if command evaluates the expression, tests the The first argument of each pair is the pattern which will be
results. If the result is true, the TCL script is executed. If the compared against the value. When the pattern matches tne
result is false, ifreturns andno further action is taken. Example, corresponding script is executed. The resulting value will be the
re_ult of the command. The switch command compares alltne
if(Sx < 0} patterns sequentially. If no pattern matches, it returns an emp'y
string without any further action. The given switch command
increments the variable t1 ifa matches with x or increments 12
set x 0
if amatches withy or increments t3 if a matches with z and
returns an empty string if no pattern matches.
WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
UNIT-5 TCL and Tk 5.11
There are three forms of pattern matching that are (iüi) foreach Loop
supported by switch command, exact, - glob and - regexp. The forcach command iterates through arrays. For each
- CXaCt of the loop the valuc of the current array element is processed
and incremented or decremented by one. It has three arguments,
-cxact is used to select the exact string comparison. It
is the detault behavior the first argument is the name of the variable, the second
argument is a list and the third argument is a TCL script i.e.,
- glob the body of the loop.
- glob is used to select the pattern that matches with the Exámple
given string. Each character.of the pattern must match foreach{a b} {1234 5)
with the corresponding character of the string.
- regexp puts *< $a>< $b>
The - regexp selects the regular expression whose single
characters match with the corresponding parts of the string. This prints
Q20. Explain the looping commands with examples. 12
34
Answer :
5
Looping Commands Q21. Explain "break'" and "continue" commands.
There are three looping commands provided in TCL, Answer :
while, for and foreach. These commands run the same script a
The break and continue commands in TCL are used to
SDecified number of times until the condition is true.
abort a part or all of looping command.
() while Command Break Command
The while command will execute the script until the The break command causes the termination of the
expression becomes false. It has two arguments, the first innermost enclosing loop immediately.
argument the expression and the second argument is a TCL Example
script. The while command evaluates the expression until Print a line for each of the integers from 0 to 5,
the result is non-zero. It terminates the command when the
expression evaluates to false and returns an empty string. for(set x 0} {S x< 10} (incr x}
Example if {$ x>5}
while{ Sx >0}
break

set result[expr Sresult * $base]


Puts x is $x"
set P[expr $P -1]

Continue Command
(i) for Loop The continue command causes the termination only of
The for loop executes the script for a specified number the current inner most loop, it continues with the next iteration.
of times. It provides more explicit loop control. It has four It is used to skip a part of à loop and continue with the next
arguments the first argument is an initialization seript, the second iteration.
argument is an expression that determines when to terminate Example
the loop, the third argument is a reinitialization script that is Print a line for each of the integers from 0 to10except 5.
evaluated after the execution'of the body of the loop before the
evaluation of test and the fourth argument is a script i.e., the For(set x 0} {$ x< 10} {incr x}
body of the loop. {'
Example if {$.x ==5}
for(set i0} {SI<i0} {incr i3}
continue

set x[expr Sx + Sy(i)] puts "x is $x"

SPECTRUM ALL-IN-ONE J0URNAL FOR ENGINEERING STUDENTS


SCRIPTING LANGUAGES [JNTU-HYDERABADI
5.12 of item as,
This command returns a list
12346567
5.1.5 Data Structures (David Alam} Radhi Raghu
structures in TCL. Davidand Alam are enclosed in a single
braces, so thev
Q22. Describe about data separated by split
OR form a sublist because they were not
in TCL with a
Explain the list data structure
character.
eliminating the subliste
sample code. If asingle list has to be made
(Refer Only Topic: List) We use,
May-13(RO9), Q5(a)
Answer : split $line {#}
There are two types of data structures used in TCL.
This command returns,
They are, eliminating
(a) List David Alam Radhi Raghu 12346567 by
(b) Arrays. sublists and spliting characters.
List llength Command
1. (v)
separated by number of elements
List is a string containing list of elements llength command will return the
spaces or tabs or new line. present in the list.
Example: India UK US Africa Germany
Syntax: llength list
If we use braces and quotation (double quotes) to group
element into sublists. Example
Example: India {UK Sa}. "UK Sa" llength $ list
If the variable a contains the value "Africa", then the in list.
This returns the number of element present
second argument with braces will be set as it is i.e., UK $a
because braces provide strict quotation and the third argument llength{a b'c d}
with quotation is the string "UK Africa". This returns 4.
Construction of List
(i) list Command llength{ }
List comm¡nd groups the given arguments as the values This returns 0.
in the list. If any argument of a list is appended with a lindex Command
special character then, the command performs automatic (vi)
quoting. This command returns a value which is identified by
In the above example, variable X is appended with a specified index value.
special character $, this will indicate that it is already a Syntax
list enclosed within braces.
Example lindex list? index .... ?
List $ X apple banana-grapeS lindex takes two arguments list of element and an index
(iü) linsert Command value, this will return the value apecified at given index.
This command return anew list formed by inserting the Example
arguments into an existing list at a particalar point.
Syntax lindex {Apple Mango Orange} 1
linsert list index value? value?... This will return Mango.
(ii) lappend Command (vii) Irange Command
This command appends the arguments at the end of the This command returns the elements of a list from the
list.
specific range.
Syntax
lappend varName value? value ..? Syntax
(iv) split Command Irange list start number end number.
split command returns a list formed by eliminating the Irange takes three argument a list, start index and end
splitting characters. index.
Example
David Alam # Radhi # Raghu # 12346567 Example
If this line is read into the variable line, then Irange list 114
split $line # This returns all the elements present in between lto 14.

WARNING: Xerox/Photocopying of this book IS a CRIMINAL act. Anyone found guilty is LIABLE to face LÉGAL
proceedings.
JNIT-5 TCL and Tk
Sample Code 5.13
#!user/bin/tclsh One-dimensional
In
Arrays
set number {10 11 12 13 14 15} TCL, one dimensional arrays are
represented as,
array set array name [list of elements]
puts [1length Snumber] /*Returns length of list*/
To set a specificvalues in the array, we
puts [l index Snumber 4] /*Returns the 4th write il as,
position of list*/ array set b(bar) 4
puts [l index Snumber 0] /* Retums the 1
position of list */ This sets bar as the fourth value in the
puts [Irange Snumber 02] /* Returns subset of array.
list| Multidimensional Array
Output
Two dimensional effect is given to the
two index separated by a comma. array by using
14

10
setSaname (1, 1) 2000
This will set 2000 value in the aname
11 12 first column. array at first row,
2 Array
An array is a collection of elements, each 5.1.6 Input/Output
its own name and value. element has Q23. Explain TCL Input/Output commands in
detail.
Initialization Answer :
Initialization of array is done in single step using array TCL Input/Output is built using strings. It
set command. with the external resources through streams, likecommunicates
stdin, stdout
Example and stderr.
array set names{ David, Alam, Rahul, Naveen Output Command
This creates the array to names. puts: puts is used to perform the basic output operations.
Extracting By default, this prints the output to stdout by
appending
In order to retrieve the elements a new line:
present in the array we
use array get command Example: puts "Hi students"
Example Option.
Foreach {key value} [array get A] nonewline: This option omits the newline which is
appended by default.
Example: puts - nonewline "enter your student id:"
Input Command
This command present prints the keys and value
gets and read are used to perform the basic input
alternatively. operations.
Retrieving (a gets
To retrieve the list of keys present in the array we use
array names command. The line given in stream will be read by get
command
and it willreturn the line by appending the new
Example line
foreach key [array names Names] Example: Gets stdin;
In order to assign the input string to a
variable we use
or giving or specifying a destination to the given
input
Modifying the Array set a[gets stdin ans]
Let us consider an array with list of earnings. When the file reaches its end, gets will either return a
array set eànings {January February March empty string or -1 according to the format of the get
command.
December}
To set a value in the.array, we use set command (b) read

set carnings (January) 7600 In a stream, if large volume of input data-is given, then
This will assign 7600 value in the element January in inorder to have a efficient block reading facility we use
Ihe array earnings. read command.
set earnings (January) Example: read stdin
This displays the value assigned to January. This returns a string including the final new line.
SPECTRUM ALL-IN-ONE J0URNAL FOR ENGINEERING STUDENTS
5.14
SCRIPTING LANGUAGES [JNTU-HYDERABAD)
Options 'proc' is an ordinary TCL command.
nonewline: This omits the final new line. TCLprocesses the
arguments to "proc' in the similar way as it processes the other
Syntax commands. To pass the argument name of 'demo' to pror:
read-nonewline stdin as single list of argument names, the braces fa b} are used.
This does not mean any special syntactic notation. Generally
If read command is following with the byte
count if a procedure contains only one argument the braces are not
argument, it reads the data given in the stream till it reaches the required but to maintain consistency most of them uses braces
specified byte count value, Similarly toavoid substitutions, theentire script body is passed
Examples: read stdin 4096 as a single argument to the proc using the braces around the
This reads 4096 bytes from the stream. last argument of proc.
eof Command
Example
lf the file reaches its end, then eof command proc fact fa'}
returns 1
otherwise 0.
while(! [cof stdin]}
if {Sa< 1}

return 1
5.1.7 Procedures
Q24. Explain about procedures.
Answer : return [expr {Sa*[fact [expr (Sa - 1}]})
The TCL command 'proc' is used to create
procedures.
Syntax Output
Proc name {argument list} {body} fact 3

Here, name' indicates the name of the ’6


procedure,
'argúment list' contains the names of the arguments (formal fact 5
parameters), body' contains the TCL script. ’ 120
Example fact 0
proc demo (x y}
’1
(expr {Sx- Sy}}
Here, the factorial function uses 'return'
makes the enclosing procedure to return immediatelycommand, which
The procedure 'demo' can be invòlved as any other
TCL the value of $a is less than or equal to 1. whenever
command. The values given in the procedure callare assigned is evaluated which recursively calls Otherwise, the 'expr
to the variables in the argument list as soon as
the fact'
the output. So, whenever we, want to avoid and finally returns
invoked. The argument list may contain a variableprocedure is
name or a script, 'return' command is invoked. executing the entire
list of variables names or a default value to
be used, if a value
is not provided during a procedure call. Q25. Explain the concept of local and global
To get the result of a with suitable examples. variables
is used, whËch returns a procedure.the command 'return' AnsWer :
particular value. In the case, if 'return
command is not used in a procedure then the last statement in ATCL procedure uses distinct set of variableswhen it is
the 'body' returns the result.
evaluated.
Invoking Demo
As mentioned earlier, the
Local variables are defned and accessed within the
be invoked only with two procedure demo' must procedure. These variables are taken from the
arguments, we see some of the procedure and are removed implicitly whenever thecaller ot a
procedure
invocations, returns. The name of local variable can match with the name of
demo 42 a global variable or namespace
varjable or other local variable
’2 in some other procedure. However, these
varjables are distinct.
demo 4 4 The command that invokes a
the values of the arguments in that procedure is used to Sel
’0
are local variables to a procedure. These argumens
demo 4 procedure. The values of local variaoie
corresponding to the arguments passed to a procedure are useu
in the execution of a procedure. The
’ wrong # args: should be "demo a b" other local yariables are
The last invocation 'demo' shows an incorrect invocation. set automatically. The recursive call to a
set of local variables for each procedure have dist
WARNING: Xerox/Photocopying of this b00k is a CRIMINAL act.
invocation.
Anyone found guilty is LIABLE to face LEGAL
proceedings.
UNIT-5 TCL and Tk
5.15
Example The procedure above, decrements a given value by
proc exponent {base a} 1. value' is the first element which has no default value.
decrement' is the second element with default value 1.The
set output 1//Mocal variable procedure dec' can be invoked with any of the two arguments.
while ($ a > 0} dec 30 2
’ 28

set output [expr Soutput * Sbase] dec 30


set'a [expr Sa 1] ’ 29

If a value is not specifies as default for an argument in a


return ^output procedure, then at the time of procedure invocation it need to be
supplied. Always the default arguments are provided at the last
in a argument list. The arguments followed by default argument
Global variables are defined outside a procedure. These must be default arguments. After invoking a procedure of any
ariables remain exist, until they are removed explicitly. 'global' of the argument specified is removed then all the argument
sthecommand used to refer the global variables in a procdure.
following the removed one must be removed.
global a b
Variable Numberof Argument for Procedures
The global varjables 'a' and b' are accessible inside
procedure. The command global' is invoked during the In a procedure, the argument list may contain any number
:xecution of procedure. The effect of 'global' command starts of arguments. If 'args' is a special name of the last arguments
when the procedure is invoked and remains until procedure in the argument list, then different number of arguments may
returns. The arguments in a 'global' command are treated as be used to invoke a procedure. Except the last argument 'args
the names of global variables and references are made to these remaining arguments in the argument list are operated in the
names in a procedure. The 'command' global can be invoked same way as earlier, we can also specify new arguments. 'args
is a list containing set of additional arguments, if there are no
at any time, after. invoking a procedure.
extra arguments then it is set to an empty string (default value).
Example
proc demo {args}.
proc exponent (base a}

set sun 0
global output lglobal variable
while {Sa>0} foreach value Sargs
{
set output[expr Soutput * $base] set sum[expr {Ssum + Svalue}]
set a[expr Sa- 1] }
return sum

Q26. Discuss about default and variable number of


arguments for procedures. Output
Answer : demo 323
Default Arguments for Procedures
In a procedure, all the arguments or some of the demo
guments maycontain default values. The argument list in ’0
iprocedure may contain a number of sublists in which each
Rublist is considered as a single argument. The single element in The additional arguments before 'args' in the argüment
isublist specifies the name ofa argument, ifthe sublist contains list of procedure are treated as default arguments.
in additionalelement (two elements) then the second element Q27. Explain call-by-value mechanism with an
pecifies the value of first element (argument). example.
Example Answer :
proc dec {value {decrement 1}} Call-by-Value Mechanism
In TCL, reusability of modules is achieved by procedures.
expr $value - $decrement They can be defined at any time. The arguments are passed to
the procedure either by value or by reference.
SPECTRUM ALL-IN-ONE J0URNAL FOR ENGINEERING STUDENTS
SCRIPTING LANGUAGES rJNTU-HYDERABAD)
5.16
command 'upvar'in conjunction with
The TCL mechanism of
The syntax of procedure is as follows, the
proc proc_name arguments ?argument s? body |

The arguments used are generally local.Global variables


above concept

Irom outside the


procedure).
supports the
Variables such as global,
context ofa procedure cal -byot-rehferereactnciNe.e
local and namespace can be acceSsed
(i.e.. from

can also be referred using the global command. often 'upvar


done by using 'upvar', is
specifically usedusefulto
This
Examplel This concept is
proe ine{ii } provide call-by-reference.
when dealing with arrays.
is a procedure to
For example, if demo'cannot which weh¡ve
CNpr Si +Si 'n'. This be done by
to pass an array, say
demo $n. Since, simplindivIduai
there are values for y writing
the command
Here inc is the procedure name. The arguments are passed value ofentire array. For this purpose,
elements and not a single
hy value. 1he arguments are specified with the default values, to a procedure as demon.
the name ofan array is send
(a) Ifwe call inc 92 2, 'upvar' is used to access the
array elements. However.
The result is 94
Example
(b) If we call inc 5,
proc demofename}
The result is 6
Example 2
proc add list upvar Senamen

foreach el[lsort (array names n ]]


set i0
foreach j Slist
puts "$el = Sn (Sel)"
inc i $j

set emp(Num) 25
Here, the procedure add has a list, wh0se elements are
set emp(Work) "Content writer"
treated as arguments. Suppose, if there are no elements, it will
be treated as empty string. demo emp
(a) If we call add 2 4 6
’ Num=25
The result is 12
’ Work = Content writer
(b) If we call add
The result is 0. Here, the name of an array is passed to the procedure
Q28. Does TCL;support call-by-reference? Explain. demo' when invoked. Using a local variable 'n', this array is
Answer :
accessed. This is done by 'upvar' command, it takes the name
of avariable as the first argument which is accessible to the
Usually, TCL does not provide the mechanism of call-by caller of the procedure. In the calling procdure, this varanie
reference. This seems difficult to change the value of a current may be a global, local or namespace variable.
variable by writing a procedure. In TCL, the variable name is a
string value which can store other variable and hence by using "upvar' command takes the name of a local variabie
substitutions one can copy the mechanism of a reference. as second argument. The variable enane on the caller is Ro
Example referred by this local variable n. where it can be accessu
set a"Helloworld". using 'upvar". The elements of global variable 'emp'are u
actual elements which the procedure demo' readsthrough
set ba
array 'n'. "Emp' is altered when procedure demo writes to n
set Sb The list of elements in a array are returned using thecommand
’ Helloworld executed
'arraynames' by procedure 'demo'. Finally, 'Isort'is
Here, the string value 'a' is substituted in $b by the TCL which sorts the elements in an order and print them. Bydefault,
caller
interpreter. The value of the variable is returned by the set the first variable name in an
'upvar command refers thelevel
command which takes the variable name as the argument and of existing
procedures content. The variables from any
executes. including global level on the call stack can be accessed.
AADNIAG: Xerox/Photocopying of this book SaokiMNAL aGt, Anyone found guilty is LIABLE to face FGAL
Droceedings.
AIT-5 TCL and Tk
5.17
ample
Example
upvar #O order a
proc increase {var{dec 1}}
To consider the variable 'order' as a global variablc
ation #0 is used, The atbove command can nccess global
iable 'order' through a local variable 'u'. upvar $var g
upvar 2 other a set of [expr $V + Sdec]
This command accesses the global variable of the caller
cxisting procedure making it as local variable 'a'. The Data Structures in TCL
ent content is denoted by level '0.2' in the above command
Ws the content of 'other' variable which is two levels above For answer refer Unit-V, Q22.
(call stack. 5.1.8 Strings
19, Describe about variables and data structures
in TCL.
Q30: Explain string operations with suitable
April-14(R09), Q5(a) examples.
OR Answer :

Write short notes on scope of variables. String Operations


In TCL, string operations are carried out by using the
(Refer Only Topic: Variables in TCL) string command. The various string operations are discusséd
SWer : below,
1. String Length ste
riables in TCL
This command returns the length of the given string, str.
TCL supports different variables and evaluates them That is, it returns the cóunt of number of characters.
thin its scope.
Example
Local variables are the variables which are defined inside
(i) String length SIA
the TCL procedure or the arguments of procedure itself. It returns 3
The scope of these variables is within the procedure and
these variables are deleted when the procedure returns. (ii) String length "SIA Publications"
Thus, it is possible to have same local variable for two It returns 16.
2. String Compare ?-nocase? ?-length num? strl str2
different procedures.
This command return's -1 if str1 < str2
Global 'variables are the variables which are defined
0 if strl=str2
outside the TCL procedure. The scope of these variable
is throughout the script. These variable must be explicitly 1 if str 1l> str2
deleted. The -nocase option indicates case insensitivity.
Namespace variables are the variables whose scope is The -length option indicates the first num characters to
throughout the context of the particular namespace. be compared.
Example
Local varíables can have same name as global variables or
mespace variables. They are treated as two different variables (),String compare Nehru Gandhi
dchanges made in one variable do not affect the other. It returns -1

The global and upvar commands change the scope of the (ii) String compare -length 3 Master Mask
nables. It returns 0
3. String Match ?-nocase? Pattern str
Global command cause the local variables to refer the
global variable i.e., the global variables can be used by This command uses glob-style matching rules. It returns
1if pattern matches the given string str and it returns 0
the procedure using global command. if it fails to match. The -nocase option is optional which
Example: global x y indicates case insensitivity.
Here, the global variables x and y can be used inside the Example
procedure. (i) String match S* SIA
The upvar command works similar to global' command. It returns 1
It helps in changing the name of the variable in current (i) String match c.t coat
scope to the variable in different scope. It returns 0

SPECTRUM ALL-IN-ONE JORNAL FOR ENGINEERING STUDENTS


5.18 SCRIPTING LANGUAGES [JNTU-HYDERABADI
String To lower str ?start? ?end? 8. Format formatstring ?value value...?
4
This command converts all the upper case characters in This command substitutes the value arguments in plaos
the given string str to lower case characters and returns of %sequence in the given format string. The resultant
the converted string. The start and end options are the string willbe similar to the specified formatstring.
indexes which when specified, the conversion starts from Example
start index and ends at end index.
(1) set name book
Example
set cost 25
() String to lower "SIA Publications"
set display [Format "This %S costs %dRs"
lt returns sia publications. Sname Scost]
(i) String to lower "SIA PUBLICATIONS" 49
puts display
Itrturns SIA publicATIONS
Its format formats the given string in a way similar
String To upper str ?start? ?end? to printf function in C. It returns the following
This command is similar to to lower except that formatted string which is stored in display.
converts all the lower case characters in the given string This book costs 25 Rs.
str toupper case characters and returns the converted
string. (i) Format "Square root of 3 is %.5f" (expr sqr(3)]
Example It returns square root of 3is 1:73205.
(i) String to upper SIA Publications" 9 Split String Splitcharacter ?split characters?
It returns SIA PUBLICATIONS This command splits the given string into substrings.
(ii) String to upper "sia" 12 It creates a list for storing the substrings. The split
character specified is used to separate the given string
It returns Sla. on its occurrence.
6. (a) String Trimn str ?char?
Example
This command removes the characters other than
1 Set msg"Apple, Mango, Grapes"
the characters that appear in chars from the given
string str and returns that string. split Smsg,
Example The split command splits the given string at the 'g
String trim education aeiou and stores it in the list. The list contains3 elements,
Apple Mango Grapes.
It trims the vowels from the given string (education)
and returns dctn. 2 Split abxycydxy
(b) String trimleft str ?char? Here, more than one splitcharacter is specified. It
returns ab{}cd
This command works similar to string trim except
that it removes the leading characters. 5.1.9 Patterns
(c) string trimright str ?char? Q31. Explain pattern matching techniques with i
This command works similar to string trim except examples.
that it removes the trailing characters. Answer : Model Paper-ll, Q1O(b)
7. Append Variablename strl ?str2? ?str3? Pattern Matching Techniques
This command concatenates the given string or strings
onto the end of the value of the variable. TCL provides two pattern matching techihiques. They
are glob matching and regular expression matching.
Note: The first argument must always bea variable. 1, Pattern Matching using Glob Style i
Example afier
This technique is the simplest one. It is named
set greeting {Good Morning} the globbing mechanism used in Unix shell for expandingItnleis
append Sgreeting "! Have a pleasant day" names. The glob-style matching is easy to learn and use.
suitable only for simple pattern matching which is accompisneu
It returns Good Morning! Have a pleasant day. by _tring match.
WARNING: XerowPhotocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
UNIT-5 TCL and Tk 5.19
The syntax of string match is,
string match pattern string or ariable.
It returns on success and 0 on lailure. lt performs glob matching using only three patterns that are listed in the table below.
S.No Pattern Deseription
1 Matches 0 or more characters

Matches a single character


[characters] Matches a single character from the given set of characters enclosed in square brackets.
Table (1): Pattern used for Glob Matching
Let us see few examples,
Set Name Education

string match *cat* Sname


1

Here, the pattern *cat* matches the string which has a substring cat, It returns 1 as the match is found in the value of the
variable name.
String match Educat? Sname

Here, thepattern Educat? match the string of length 7 and which starts with Educat. It returns 0 as the match is not found
in the value of the variable name.

String match ?ure sure

Here, the pattern ?ure matches a string of length 4 that ends with ure. It returns 1 as the match is found in süre.
String match *sure sure
1

Here, the pattern *sure matches a string that ends with sure.
String match {[A-Z]}*} university
0

Here, the pattern ([A-Z]*} matches a string startingwitha capital letter.


ivi String match -nocase U* university
1

Here, the -nocase option indicates case insensitive. The pattern U* matches a string starting with uor U.
vii) String match *12} why?

Here, the pattern (*\?} matches a string ending with? (Question mark).
vii) Set files {prog.c xyz.htmlprogl.c stdio.h}
string match *.[ch]$files
1

Here, the pattern *.[ch] matches all strings in $files ending with either .c or .h.

SPECTRUM ALL-IN-ONE J0URNAL FOR ENGINEERING STUDENTS


SCRIPTING LANGUAGES [JNTU-HYDERAEBA
5.20
Expression matching is done...
2. Pattern Matching using Regular complex pattern matching. The regular expression
and is used for
This technique is very powerful
the regexp command.
command is,
The syntax of regexp
(a) regexp pattern string
and O on fuilure
Itreturs l on succcss
variable.
(b) regCNP pattern string pattern is stored in the variable.
returning the value Ior 0, the string that matches the
In this casc, apart fhom table below.
expression matching using the patterns that are listed in the
l perlorns rcgular
Description
S.No Pattern
Matches a single character
string
Matches the position at the beginning of input
3. Matches the position at the end of input string
4 Matches 0 or more characters of the previous pattern
5. Matches lor more characters of the previous pattern
6
Matches 0 or 1character of the previous pattern
characters enclosed in square brackets 1.
7 Matches a single character from the set of
string enclosed in brackets ().
8. ) Matches a string which has a substring similar to the
9. Matches the alternate character

10. alpha Matches a letter


11. upper Matches an upper-case letter
12. lower Matches a lower-case letter

13. digit Matches a digit


14. xdigit Matches a decimal digit
15. alnum Matches an alphanumeric
16. print Matches an alphanumeric (same as alnum)
17. blank Matches a space or tab character
18. punct Matches a punctuation.
Table (2): Patterns used for Regular Expression Matching
The patern numbered 1to 9are supported in TCL 8.0 where as the remaining patterns 10 to 15 are supported in TCL &.
Let, us see few examples,
1 Set message {Hi! your id is 591}
regexp {^i} Smessage
It matches strings that start with i. It returns 1 as the strings id start with i.
2. regexp {^ [A-Za-z] + $) Smessage
It matches the string that starts and ends with acharacters. It returns l as the strings your 'id' is start and end with acharacte
3 regexp (^I[: digit:|]] +$} Smessage
It matches the string that starts and ends wih adigit. It follows the syntax of TCL 8.1. It returns 1as the string 591 start
and ends with a digit.
4. regexp {C.t} "Education} var
When any variable (Ex: var as mentioned above) is specified, it, matches the given expression to the string and stores u
nart of the string that is matched in th¡t variable. To view the contents of var, post is used.
post $var #returns cat

WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
AD) UNIT-5 TCL and Tk
Q32. Explain the use of switch 5.21
command for pattern Let us look at few
ing matching. exanples.
Answer : set var "xyz"

Switch Command of Pattern Matching switch xyz.


The switch conmmand
executes one of the X -

scripts, depending on which the pattern matclhes. several TCL b {expr{1}}


The syntax of switch is as follows, $var (expr (2}}
1.
Switch ?option? string pattern body ?pattern default {expr(3}}
body...? }
Switch ?option? string {pattern body ?pattern Here, the string argument, xyz is matched with
body...?} the
lt matches the given string variable, var. It returns 2 after evaluaion
against the given pattern.
Once the pattern matches the string, it 2
the body.
evaluates the body by switch -glob xxxy
Ncursively passing it to the TCL interpreter. The last pattern {
argument is generally defaults. If the pattern X*y {expr{1}}
not match the string and if argument does
default is not mentioned then this
comnnand returns an empty string. x*
{expr{2} }
The option argument can be either of the default {expr{3}}
start with a hyphen (-). following.They
(a) -eXact Here, the switch command uses the glob-style
It returns l after evaluating the body. matching.
This is a default opiton. It follows 3. switch abc
exact matching to
match the string against the pattern.
(b) -glob m

This option follows glob-style matching to (expr{1}}


match string default {expr{2}}
against the patterns.
(c) -regexp Here, the string argument, abc fails to match the
This option follows regular -expression specified. Thus, the default clause is taken and patter1ns
matching to it returns 2.
match the string against the patterns. 5.1.10 Files
(d) -nocase Q33. Explain about associating a stream with a
or pipe. file
This option follows case sensitivity while matching the Answer :
string against the patterns.
(e)
Associating a Stream with aFile or Pipe
-matchvar varname The open function isused for associating a
This option is used along with -regexp option. The list a file or pipe. The name assigned to the stream with
stream is called the file
of matches found by the regular expression engine are descriptor. The predefined stream for input output are stdin,
stdout and stderr.
stored in the variable specified (i.e., varname).
The syntax for open command is as follows,
-indexvar varname (a) Open filepath ?mode? ?permission?
This option is also used along with -regexp option. The The filepath specifies the path of the file to be
list of indicesthat refer to the matching substrings found The mode determines how the file can be opened.
accessed. This is a
by the regular expression engine are stored in the variable optional argument.
specified (i.e, varname). It can ber, rt, , wt, a, at.
By default, it is read only i.e., r
The permission determines who can access the file. This
This option marks the end ofoptions. An argument which is also an optional argument. By default, it is 0666 i.e.,
follows this option will be treated as stirng. It is not used Example
when pattern and body arguments are grouped together
into single argument.
Set cfile [open/temp/prog.c w 0600]
puts Scfile It opens a cfile".
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
5.22 SCRIPTING LANGUAGES [JNTU-HYDERABADI
2. Buffering Value
(b) Open/con1mand ?access?
The command is treated as alist and is executed by (a) If value =full, the output is buffered by the I/O system
creating subprocess. Based on the accessed specified it cxecutes until internal buffer is full or until flush command i
pipes for writing/reading the input/output to/from a pipcline. It invoked. By default, -buffering is set to full excludi
returnan identifier for communicating with the subproceSS. the channcls that connect to terminal like devices.
Example (b) Ifvalue= line, the output is automatically flushed bvi
/O system when output is newline. This value is set
Set pipeto lopen'abe w] initial value for channels that connect to terminal lit.
This opens a stream for writing, The input that is sent devices.
by puts to this strcam will be piped into the standard input of If value = name, for every output operation I/O systers
command abe. The standard output of abc is sent to the standard (c)
willflush automatically.
output ofTCL application. The syntax is similar to perl. But, in
perl the bar is put after the process name to indicate read from 3. -Buffersize Size
The value option, size must be an integer. This onti
In TCL the bar is in the front to indicate 'pipe' and that sets the size of buffers that are allocated for channel to store i
the streanm is open for reading as shown below. bytes.
Set pipefrom [open/abcr] 4. -eofchar char

It attaches the stream to the standard output of abc. -eofchar finchar outchar}
Suppose a 'pipe' stream is opened in rt mode i.e., for This option is used to set the end of file marker, It is
reading and writing as shown below. supported by DOS files systems. The value option, char can
Set pipe [open/abc r+] be a empty string or a non-empty string. By default, the value
is empty string except for the files under windows. The inchar
It sets up two pipes, one for writing to abc's standard and outchar specifies the end of file marker for input and output
input using puts Spipe. respectively.
Another for reading from abc's standard output using 5. -translation mode
gets Spipe.
-translation {inMode outMode)
Q34. What is the purpose of the fconfigure command?
This option is used for marking end of line. The end of
Answer :
line in TCL scripts is represented using newline character (n).
fconfigure Command In different platforms or in same platform different devices, the
representation of end of line is different. The value option mode
The fconfigure command is used for performing set and can be auto, binary, cr, crlf and lf. It is by default auto for input
get options on a channel.
and output.
The syntax of fconfigure is as follows, When the input mode is ON the TCLIO system translates
(a) fconfigure Chid the external end of line representation into newline characters.
The chid parameter specifies the channel for which an And, when the output mode is ON the TCL JO System translates
th newlines into external end of line representation.
option has to be set. It returns a list that contains alternate
option names and values for the channel. The performance of the translation mode when specified
(b) fconfigure Chid Chname as input and when specified as output is discussed below.
1. auto
Here, the parameter chname is specified. It returns the
current value of the given option. In input mode, it translates newline (U), carriage return
(c) Fconfigure Chid Chname Chvalue ?chname chvalue? (cr) and crf (carriage return followed by a newline) into end
of line representation.
Here, a pair or pairs of name and value are supplied. It
sets each of the named option to the corresponding value Whereas in output mode, it chooses different
option and returns an empty string. representations for different platform.
The options supported by all the channels are discussed For example, for sockets on any platform, it uses crl.
below. On unix platform, it uses If. On Macintosh platform, it uses cr.
1 Blocking Boolean
On windows, it uses crlf.
2. binary
Thisoption tells whether the I/O operations (gets, read,
puts, flush,close) on the channel block the process indefinitely. In this mode, no translations are perfornmed during inpul
The value option must be only a boolean. or output. This mode is much similar to lfmode.
WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to»face LEGAL proceedings.
UNIT-5 TCL and Tk
5.23
3. Cr

Examples
In this mode, the end of line is
represented by a single
çarriage return character. When the input mode is ON Set vars {xy z}
it
translates carriage returns into newline characters. And when for eachn $ vars
the output mode in ON, it performs reverse translation. It is
used on Macintosh platforms.
4. crlf unset Sn

In this mode, the end of line is


represented by a
return character followed by a newline character. When carriage
in input Here, the single unset command takes a number of
mode, it translates the carriage return-newline characters into arguments and tries to unset them as it is in the "foreachloop".
newline characters. And, when in output mode it performs 1.
reverse translation. It is use on windows platforms and for Set vars -
network connections. unset S vars
5. Here, the variables are passed as single argument to the unset
In this mode, the end of line is represented by a single command. So 'unset' tries to unset avariable named as abcd.
newline character. Notranslations are performed during input To make the above code work, treating, the variables
or output. It is used on unix
platforms. as separate arguments the (*} syntax is used for arguments as
shownbeclow,
5.1.|AdvancedTCL-eval, source, exec and
uplevel Commands 2. Set varsa b c d)

Q35: Explain the folowing commands, unset {*}$ vars


(a) eval The same thing can be done by using the 'eval' command,
(b) uplevel. which creates a new form of acommand, unset a bed by
Answer : concatenating all the arguments. This new command is finally
(a) eval passed to TCL for evaluation.
The creation and execution of TCL script is done by 3. eval [concat unset S vars]
the 'eval' command. This 'eval' command takes a number of eval unset $ vars
arguments and concatenates them using a separator 'space'. It
then calls the interpreter to execute the output (resulting The two codes shown above are similar to each other.
as a TCL script. The most common use of'eval' is that it string)
allows The variable names are treated as separate arguments to unset
all the TCL parsing rules to be applied to the script. By this, both the cases.
the script contains a large number of commands, comments,
multiple lines etc. The commands generated by 'eval' are stored (b) uplevel
in variables and are later executed as TCL scripts. The uplevel' command is the combination of 'eval'
Example and "upvar' commands. This command allows a script to be
sèt clear interpreted in a specific context. A relative or absolute stack
frame number used with uplevel denote the level similar to
set x 0 upvar and the detault value is 1.
set y 0 Q36. Explain the following commands,
(a) source
eval clear
(b) exec.
When the command 'eval' is invoked, the variables
in the script are set to 0'. The only use of 'eval' in the above Answer :
example is that the two set commands are executed directly. (a) source
The advantage of 'eval' is more useful in dynamic processing
of creating the script. This command takes the file nanme as an argument. It
Generally, when parsing a command the TCL allows two invokes the interpreter to execute the content of a file as TCL
levels of parsing. One level of parsing and substitution is with script. The syntaX of this command is as follows,
the use of 'eval' command. Another level of parsing is done,
where result of one substitution is provided (reparsed) to another source ? - encoding encoding? fileName
substitution. This scenario is useful when a variable contains a encoding in the syntax is used to specify the encoding,.
list of items, or a return value with a list of items and when the If ençoding is not specified then TCL reads afile using system
values in a result are passed separately to the command.
encoding.
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
5.24 SCRIPTING LANGUAGES [JNTU-HYDERABAD)
Example (c) If aspecial symbol example!! is included in place of the
source demo.tcl command name then the previous command is inyoked
The file can be specified either using relative or absolute again.
path. The file demo.tcl is executed as a seript. T'he return value (d) If a command, which exists already has a unigue
of source command is the value returned from the last command abbreviation which is similar to the command name then
in the file.
after the expansion of abbreviated command name, the
(b) èxec command is called again.
The 'exec' is implemented on systems that support
process creation. The tirst argument specifies name of executable The autoloading process initially makes the 'unknown'
file. TCL searches tor the matching file specified as argument command aware of the library files. If this is fulflled then the
andexecutes the file in a different child process and waits for 'unknown' command locates the library file, sources it and then
its completion. re-invokes the original command. This is donewhen a library
Example procedure is used for the first time. But, if the command is used
later then autoloading is avoided as it will be defined.
set today[exec date]
The date command of the system is executed and the Q38. Define package. Explain about the creation and
value returned by it is stored in the variable "today". usage of a package.
Note Model Paper-l, Q10(a)
Answer :
This command is not confined to system commands.
5.1.12 Namespaces Package
A package may have any number of versions. The script
Q37. Explain the autoload feature of TCL.
can impose condition on the required version.
Answer :
A package can posses different TCL procedure definitions
The command unknown' is invoked by the TCL
interpreter, when it finds a.new command that does not exist. and commands in C. The mechanism of package is similar to
The name and arguments of the original command are passed the autoloader.
to the unknown command.
Some improvements are made in the autoloader to result
Example packages.
Set a20
Creation of a Package
createdatabase library Sa
Here, the createdatabase command is used.. But, if The script files are available in different directories
createdatabase command does not exist. We rewrite the same similar to autoloading mechanism. The command used to
using the 'unknown' command as shown below, implement a package in a file is 'package provide'
.

unknowWA createdatabase library 20 Example


Before the invocation of the command 'unknown' as the
substitution are performed. package provide utils 3.1
The default version of unknown' command is that it :. Here, the library file implements 'utils' package whose
performs the following operations as provided by the TCL version is in the format 'major.minor' (i.e., Version 3.1). The
system.
change in the major version number indicates a significant
(a) If the procedure defined in alibrary file is the command, change to the package whereas the changes in the minor version
then it find out the source of procedure to re-invoke the
number indicates backward compatibility. The same paçkage
command. This process is called 'aùtoloading. can be implemented byanumber of library files. The concept
(b) If the command name is same as that of program name of packageis on abstract one. That is, it is placed on the topof
then 'exec' is used to execute the program. We call this a physical file struture.
as 'autoexec'. Any Unix shell command ean be used
by the TCL Script running under UNIX environment. pkg mk Index is a TCL procedure which providès the
Example, if wetype 'ls' command then the files in the list of procedures in a package.In the form of an Index similar
current directory are listed by the unknown' command to autoloader.
which invokes 'exec ls. The commands such as standard
input, standard output, and standard error are all to be re Example
directed to the corresponding TCL channels in the case if pkg_mklndex {c:\tcl\liblutils}*.tcl
command cannot perform redirection. This behaviour of
'exec' is different from normal behaviour. It allows more The variable auto-path is set to list the directories that
and vi to be involved directly from a TCL application. contains library files.
WARNING: Xerox/Photocopying of this book is a CRIMINAL act. Anyone found guilty is LIABLE to face LEGAL proceedings.
UNIT-5 TCL and Tk 5.25
Usage of a Package In the above example, the namespace block contains 'a'
The command 'package require' is used to specify a defined by the command 'variable', It is different from the 'a'
package which is used by an application. defined outside the namespace. This is because a namespace
creates new naming context.
Example
package require utils The notation for referring the variables inside/outside
a namespace is similar to the way in which pathnames are
The procedures in a package are not loaded whenever referenced in a hierarchial file system. The::a is used to refer
the 'package require' command is invoked but as per the the outer 'a' inside the namespace whereas utils ::a is used to
requirement of an application they are autoloaded,when called refer inner a' outside the namespace. Here, ::a and::utils :
for the first time. :a are absolute names and utils : :a is a relative name. These

If the following is specified, names are determined from the global nameSpace, in which the
nameSpace utils is nested inside it as shown below.
package require utils 3.1 set a 0
Then the package versions preceeding the version '3.1
willnot be used. Ifthe package versions succeeding version 3.1 namespacè eval utils
exits then they may be used.
Q39. Discuss briefly about namespace in TCL. variablea
Answèr :
April-14(R09), Q5(b)
Apart from variables names, the TCL'procedure names
set a 2
also,occupy the global name space. For small scripts, the
concept of global name space is sufficient. But, for large scripts, n¡mespace eval file utils
it is difficult to differentiate the names when using
libraries. {
This problem can be solved by using the naming conventions
provided prior to TCL 8.0. But, this does not provide a unique variable a
solution. The concept of namespaces available with TCL 8.0,
provides separate memory contents for both the variable and
procedure names within the global scope. This avoids the set a. 4
difficulty of differentiating the names when using libraries.
Using ramespaces
The namespace eval' command is used to set and occupy
a namespace. The absolute name:: utils::file utils ::a can refer the
innermost 'a'.The relative name file utils ::a is used to access
Example 'a' from the namespaçe utils.
set a 0
In anameSpace, ifa variable is declared using 'variable'
namespace eval utils command, outsidea procedure then it becomes global to all the
{ procedures in that nameSpace.
variable a Example
namesp ace eval utils
{
set a 2 variable a 0

The variable 'a' has a initial value '0 which is used


The first argument which is followedby the.'namespace by all the procedures in 'utils' namespace. In other words, the
eval' command recognizes the namespace. In other words, the command variable is also used to initialize the variable with
second argument is the script to be evaluated in the recognized initial values.
namespace. In the same way, the variable command when used inside
The 'namespace eval' command creates a new namespace a procedure, a global variable in a namespace can be accessed
if a namnespace does not exists. in a procedure body which resembles global command outside
the namespace.
SPECTRUM ALL-IN-ONE J0RNAL FOR ENGINEERING STUDENTS
SCRIPTING LANGUAGES rJNTU-HYDERABAD)
5.26
call backs.
Example Q41. Discuss about
AnsWer :
namespàce eval utils
Call Backs
The script that are provided
i to an event
Variable a (0 b I application
will exccute it whenever theclick.
driven application.
encountered
proc demo (a} such as key press or
mouse These callbacks are an event
confirm
variable b
by default in a global
are evaluated in a
scope. To that
specific namespace context. these
the
càl executbacksed
fol ows,command
button is
'namespace code' is used. A defined as
button .B1 -command {puts Sa!
When the button is pressed its associated
executed.
with variable
Script gets
Q40. Explain the commands for importing and If the above command a' is
exporting namespaces.
Answer :
can'be clearly stated that the
in a namespace then it and not the
belongs to the namespace
encountered
global scope variable 'a'
by
Exporting namespace the above command as follows,
button .Bl-command (namespace
modifying
The 'namespace export, command is used to access the
library procedures without the need of relative (fully qualified) 5.1.13 Trapping Errors
code(puts Sa})
names. The export commnand is defined before the procedures
in the namespace. This command lists the procedures names Q42. VWrite briefly abOut trapping errors,
that can be seen outside a namespace. By default the global Answer : Model Paper-ll, Q10(b)
namespace does not export any command.
Generally, errors in ascript mákes the1 TCL
Example to Illustrate Export Command abort all the active TCL commands. Sometimes, it interpreter
is to
namespace eval utils to execute the entire script even when the script contains errors. necessary
For this purpose, we use the command "catch". This command
variable a 0 ignores the error statement and allows the interpreter to execute
the remaining script. The usage of catch command is sh
namespace export x, X, below,
proc x, {x y} catch {Script}
{ The catch command performs error trapping. It returns
variable a "0° if the execution of script is completed normally, otherwise.
it returns1' indicating error condition. The script is provided as
}
an argument to the catch command, which evaluates the script.
proc x, {x} To understand the usage of 'catch' command consider
an example in which a process tries to open a file and read the
data. To check whether a particular file exists and the process has
variable a access to.the file (for reading), the TCL provides file readable
command.
Though, the file exists, there are chances that another
process may remove it before the user gets a chance to open
Importing namespaces and read it.
The commands that are exported can also be imported
using the namespace import' command..By- default, this
Example
command do not override any of the previously imported open demo.txt
commands. In case the clash between an imported procedure could not open "demo.txt": errormessage
name anda local procedure occurs then an error is raised. To no such file
explicitly override the existing commands force option is used.
To delete the previously imported commands other than the Toovercome this problem catch is used. It ignores e
errors in open command by writing a_ followS,
existing commands 'namespace forget' command is used.
namespace import demo ::x, demo : :x, catch {open demo.txt}
or

namespace import demno :: * .The return value of catch determines the success/failure
of open command. Since, the indicates
return value is 1, It second argument
Note failure. Another form of catch' contains the
In theglobal namespace, the importing and exporting of as shown below,
commands by library packages is not allowed. catch {script} variable
WARNING: Xerox/Photocopying of this book 1s aCRIMINAL act. Anyone found guity is LIABLE to face LEGAL proceedings.
UNIT-5 TCL and Tk
5.27
The second argument specifies the name of thevariable.
It is used to store either the return This identifier cancels the pending timer events. The
value or the error message. variant of after command cancels the pending events
catch {open demo.txt} pscudo as shown
below,
1 Example
set pseudo after cancel sum.
could not open "demo.tx(" : no such file 2. Idle Events
If the open command These events are self explanatory events. Whenever
'pseudo' would contain 0'as the terminates successfully then
return value indicating success. the system has nothing to do, these events are raised. If the
In this case, it holds an error first argument of 'after' command is idle, then the command is
message as the 'open fails to
terminates successfully. executed indicating idle moment.
3.
5.1.14 Event-driven Programs File Events
To register the file events, the command 'file event' is
Q43.Explain the concept of event driven programming. used. The read and write handlers for a channel arespecified by
Answer : (Model Paper-1l, Q10(a) | April-14(R09), Q6(a) this command. These handlers are called whenever the channel
is opened for reading or writing. It is mostly used with pipes and
TCL is basically designed as a network sockets. In a pipe, if there is no data available toread,
But, at present it supports event driven command line system. then the request blocks. To avoid the blocking of a request we
model of TCL can be easily understood programming. The event
as the event and their use file events.
associated commands are registered by a script. If an active
event loop is available then, whenever an event is Example
the
commands are executed by the system. encountered, set n [open \cmd 1"]
The Vwait' command is used to control the # Read handler is registered
event loop.
Example file event Sn readable [list read handler Sn]
set a 0

Vwait a Read Event Handler

The variable 'a' acts as argument to the command Vwait. This eventhandler uses 'gets' to read one line at a timne
This is the starting point of the event loop and the event inorder to overcome the danger of blocking when there is no
process
continues till the value ofa' is changed by some event handler. data available in the pipe. The handler will be called immediately
Finally the Vwait command returns. after its existence, when not more than one line or block is
available.
There are three classes of events. They are as follows, Assóonas, end of file is reached the channel gets ready
1. Timer events to read the data, which causes the handler to be called. So,
end
of file with in the handler is checked and the
channel closed.
is
2. Idle. events This automatically unregi_ters the handler.
3. File events. The following code shows, how a read handler is called
1. Timer Events repeatedly which is previously regiatered and not checked for
end of file.
These events are raised after the specified time is
completed. The command 'after' registers timer events.
proc read handler (pipe}

Example
global line
after 250 [list proc argl arg2]
iffe of Spipe]
After 250 milliseconds the procedure 'proc' s called
with argl and arg2.
after 500 close $ pipe
return
This has only one argument which indicates the application
to be paused for specified time (i.e., 500 milliseconds)
The value returned by 'after command is used to identify #reads one line at a timne.
the event.
gets Spipe line
Example
set = sum [after 500 [list proc argl arg2]]|

SPECTRUM ALL-IN-ONE J0URNAL FOR ENGINEERING STUDENTS


5.28 SCRIPTING LANGUAGES [JNTU-HYDERABAD)
Sometimes, the close operation on ahandle may fail. Example
Thus, it is explicitly closed as shown below, The look-up facility provided by a website takes the
if [e of Spipe] query entered by a user when submit button is clicked. This
query is then passed to CGI program on the server, which
resolves it and sends the response in the form of a webpage to
iflcateh (elose Spipe}| the browser. In the format specified by a brówser the request
is sent to the server, this done by a TCL application which
makes a connection to the server. The response from the server
tileevent Spipe readable
which is in HTML form is gathered by the application to extract
the useful fields for providing answer to the query. Similarly.
a TCL application can setup connection to apop3 mailserver
return and send a request. In this case the server returns the number
of unread messages in the form of lists.
Scripting languages hide the complexity of operations
Here, empty string is registered as the newhandler. to especially when using libraries and packages. Thus, they are
cancelthe existing handler. becoming powerful. In these languages, only few lines of
code is sufficient to complete a task whereas languages like
Non-blocking /O
C' requires pages of code. The above described interaction is
Toread a pipe we can set event driven model. However, unimportant when considering the HTTP packages available
there is a possibility of an application being blocked. If there with TCL distribution. The usage of HTTP package discussed
is some data available in pipe then the event 'pipe readable' is below,
generated. The HTTP Package
The "gets" in read handlermay blockifthe pipe has only It is not an easy task to retrieve a webpage from any
a partial line. In order to escape from this situation the pipe is server. The following code retrieves a webpage i.e., home page
set to 'non-blocking' mode as shown below, from the server www.OXygene.com
set a [open \cmd 1"] package require htp 1.0
fconfigure Sa -blocking 0 set token [: :http: :geturl
# read handler is registered www.oxygene,com]
The token that identifies a state array is the value of the
'token'. This state array contains the result of the
When there is no data available in the pipe and when transaction.
upvar # 0 $token state.
'gets' is called on a non-blocking channel, it will return -1.
Here, the read-handler should be altered in such a way The above comnmand converts a token
does not perform any thing when -1' is returned (i.e.,
that it The page body /s available as state. The elementsinto an array.
that an array
ignore the case).
simply possess are as föllows.
1. current Size
Only in a non-blocking channel there is a
possibility of
blocking write operation. But, this "situation", rarely This element gives the number of bytes
occurs. sent.
5.1.15 MakingApplications'Internet-aware' 2 http
Q44. Discuss about making applications intérnet This element gives the reply status of
aware. 3
HTTP.
error

Answer : This element displays the error code if a


Thedata stored on different servers such as aborted. transaction is
mail servers, FTP servers, Newservers, POP/IMAP 4. url
Webservers etc., is
available through internet. Thus, internet becomes Tich source This element provides the
of information. There are many ways to access the
information requested URL.
Status
webserver and FTP server. One such way is by using the Web
browser. Similarly, information on Newsserver and mailserver This element can be OK, end of
file (eof) or reset
can be accessed using expert clients. The application that can 6. meta
access information without manual involvement of a server is
'Internet-ware'. This element consists of a list of {key
reply header which are extracted from value} pairs in
<META> tags.
WARNING: Xerox/Photocopying of this book is a CRIMINAL act.
Anyone found guilty is LIABLE to face LEGAL
proceedings.
UNIT-5 TCL and Tk
5.29
7. type 3. Server Socket
This element returns the type of content Server socket provides access to multiple connections.
8. totalsize When a connection is established with the well known
port, then a new socket is created and the server listens to the
Thiselement returns the total size of the data provided.
further requests.
The above Sclenments of' a state array can be retrieved Server sockets are wellknown as listening socket.Server
using individual functions given below, sockets are created by using socket command with server option
(i) ::http :: data $ token as shown below,
The URL data of the state array is returned socket - server command ? options ? port
This will establish the server socket on the current host
(ii) :: http ::status S token
at a given port number. Servername can also bc passed instead
The status element of the state array is returned. of port number depending on the operating system.
(ii) :: http :: code $ token Q46. Explain about the creation and usage of sockets.
Answer :
The http element of the state array is returned.
Socket is created using the socket command. It is
(iv) :: http :: size $ token a network communication channel that provides two way
The current size element of state artay is returned. communication between the processes on different machines
(i.e., the client and the server)
5.1.L6 Nuts and Bolts Internet Programming Syntax of Socket Command
QA5. WNrite the nuts and bolts of internet To set up a socket, its first argument should be domain
programming. Dec.-14(RO9), Q5(b) name or host nane, even numeric IP address is acceptable.And
OR the second argumnent should be port number.
Write down the núts and bolts of internet TCL sets the socket using a single statement, but
programming. programming languages like Cneeds thirty lines of code to set
up a socket.
Answer : (Model Paper-l, Q10(b) | May-13(R09), Q5(b)) Example
Servers, sockets and server socket are considered as nuts
and bolts of internet programming. set mysocket [socket localhost 8080]
1. Sockets Above statement will open a client side socket on the
local system whose port number is 8080. It returns å channel
Originally, sockets were feature of Berkeley UNIX. identifier which is to be stored in a socket.
Later, they were adopted by UNIX system. Thus, it became the
defacto to mechanism of Network communication channel. The socket programming can be clearly explained using
Socket is a network communication channel that provides
a simple script to access a POP3 server and find if there is any
two way communication between the processes on different
mail waiting.
machines. By simple client sèrver interaction POP3 client will
Example retrieves the mail from the POP3 server.
The Window 9x and Winsock NT4 have built in sockets. The conversation between the client and the server is
The winsock package provides window the similar functionality. discussed below,
It allows the window system to communicate with UNIX system Client : establish connection
over the network.
Server : + OK POP3 penelope V 6.50 server ready
2, Servers
Server will wait for the username. If the given user name
Server is ontinuous proçess that manages access to
various resources.
its accepted, it will prompt for password.
Client : USER xyz
Example
The HTTP server provide access to web pages and the Server:+OK User name is accepted, password please
FTP servers retrieve the file using file transfer protocol. Now, the server waits for the password. If the password
Every socket contains a port number by which server entered is correct, then the server will respond by displaying
client connection is established. the number of messages new present.
Server establishes connection on well known ports which Client : PASS 12346
is specified by the client during socket creation. Server:+ OK Mailbox open, 2 messages
Example Note
The port number 80is used by the client to communicate If the operations performed are successful, the message
with a web server.
willalways start with +OK.
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SCRIPTING LANGUAGES [UN
5.30
cRABAD)
Example connected 0};#3 min
Q47. What are the problems with 'network 12000 {set
programming? Suggest solution to overconme after
if(catch {socket -asyne www.xyz.com 8080} status)
these problems.
Answer : puts connectionfailed"
The problems associated witlh network programming are puts "$ status"
as follows:
1 Failed conmections
exit
Connection timeout
Non-blocking l/0.
1. FailConnection else
fails to
This problem arises when a socket command
connet the client and the server. set mysocket $status
Example writable (set
If the host specified does not exist then the exception fileevent Smysocket connection 1;
will be handled by catch. V
wait connected
if [catch {socket www.xyz.com 8080} status]
if!connected
puts stderr $ status
responding"
} puts stderr "server Not
else
exit
set mysocket $ status

2 Connection Timeout
If the server is busy, then the request made by the user is 3. Non-blocking I/O
put in a queue and is allowed to wait in the queue till the server Network connection are delayed by keeping the request
accepts the request or refuses the request. request
in the queue. Until the server respond's to the request, the
- async option should not freeze. This is achieved by setting the socket channel
If the socket uses -async option, then it immediately to non-blocking mode.
returns even if the established connection fails. Hence; the
socket becomes writable. A fileevent is used to recognise this, 5.1.17 Securityy Issues
which is as follows,
set mysocket [socket -async www.xyz.com 8080 Q48. Explain slave interpreter and safe interpreter.
fileevent $sock writable (set connected 1} Answer : Model Paper-ll, Q11(a)
Vwait connected.
Slave Interpreter
Until the fileevent is set to value connected 1, Vwait blocks
A slave interpreter is a TCL interpreter that run as a
all other requests and runs the event continuously in a loop.
The value of the variable connected will be changed separate process under the control of master interpreter.
after certain time using a timer event in low cunning. This is A slave interpreter creates a new instance of TCL
discussed in the example below, interpreter that has its own global and procedure namespace. It
Example does not have privileges to access the variables or procedurs
after 12000 (set connected0}: #3 min of the master with an exception of sharing only environment
set mysocket [socket - async www.xyz.com8080] variable is used between the master and the slave.
fleevent Smysocket writable {set connected 1} Creation
Vwait connected Aslave interpreter is created using the interp commanu.
if! connected It is followed by create and name of the interpreter 1e
demointerp..
puts stderr server connection timeout"}
interp create demointerp
exit waits
Now, demointerp is run as a separate process. It
for the script to interrupt so that it gets evaluated using
If the connection established is timeout, it will exit
running the request.
interp eval demointerp {puts Hello this scann
Catch is used to handle the exception, when a wrong This can also be written as,
address is requested. demointerp eval {puts "Hello!, this is slave\n")
WADAAG: Yerox/Photccopying oT this booR IS d oNIMINAL act. Anyone found guilty is LIABLE to face I EGAL
Droceedings.
5.31
UNIT-5 TCL and Tk
This eval command will return the value of the last Source and L0ad
that exist
expression evaluated in the slave that provides communication aliases can be done on files
The source and load the master when
between master and slave. If the current script evaluation is are provided by
nletedslave waits for another script. This process is repcated in the list of directories that
safe interpreter is created.
otil the slave is killed by master using interp delete command
as follows, Exit
slave interpreter.
interp delete demointerp The exit alias terminates the
Safe Interpreter File
access to the sub commands
The safe interpreter is a mechanism which handles the The file alias provides safe accessed by
the local file system is
oituations like parsing of TCL scripts which are embedded of thefile command. Since, information is leaked. That
the
suithin a web page, e-mail message or. in some content where source, load and file commands, to avoid
made disclosed. Inorder
code creator is not known.
is, the directory structure is
this information leakage, tokens are used instead of file name
The safe interpreters are nothing but slave interpreters These
commands in the safe interpreter.
that have a special flag set during creation using safe option. as an argument to the name.
This isshown below, tokens are translated to the real directory
interp create safe demosafe Example
source file. It has the
It hides allthe commands such as exec, open etc., which Master interpreter mediates the
interpreter that maps the token
are made accessible only when master interpreter makes an virtual path system for each safe local file system. This
explicit call to them. accessibility into a real path name on the knowledge about
invokehidden Command
prevents the safe interpreter from gaining
which is executing the
host
the file system structure of the
This command is used by the master interpreter to invoke interpreter.
the hidden commands. They implement asafer version of the descriptors
source file, checks whethr it is a TCL script file in the TCL Q50. What are the two ways of passing file
between master and slave?
library or not by using the source command as shown below,
interp invokehidden demosafe source $file Answer :
slave and
The interp expose command is used to make a hidden The file descriptors are sh¡red between the
them. The two
command permanently visible. the master so that the file is accessèd by both of
and slave are
interp expose demosafe pwd ways of passing file descriptors between master
as follows,
Here, the pwd command is made visible to demosafe. A Using Share Command
master interpreter can even hide the commands other than the 1.
default hidden c¡mmand list by using the hide command. The first method to share the file descriptor between
interp hide demosafe after master andslave is using the share command. The master opens
Here, the after command is hidden in
demosafe a file for writing. Using
interpreter. set filel[open/xyz/demo]w0666
from the
If a particular command has to be removed Now, the file descriptor is shared by the slave using,
interpreter entirely we use eval as shown below,
interp share{ }$filel demo
interp eval demosafe [list rename after{})
Here, the after commandis removed from the
demosafe Here, {} represents the current interpreter. And, the
channel gets closed only after both the interpreters reach the
interpreter. close command either implicitly or explicitly. The I/o channels
Q49. What is meant by safe base? accessibility will also be automatically closed in an interpreter
Answer : as soon as it gets destroyed
The safe base implementation is done:: in safe 2 Using Transfer Command
module. It provides privileges to the master interpreter to Alternative method to share the file descriptor between
create safe interpreter. The safe interpreter consists of all the masters and slaves is by using transfer command.
predefined aliases like source, load, file and exit commands.
The autoloading and the package mechanisms are enabled for interp transfer $filel domno
this use. This closes the master interpreter implicitly and transfers
Safename the file descriptor to the slave interpreter. To have complete
The safe namespace containsall the commands provided control over the file that is transferred, alias command is
by the safe base in the master interpreter. combined with transfer command.

SPECTRUM ALL-IN-ONE JoURNAL FOR ENGINEERING STUDENTS


SCRIPTING LANGUAGES JNTU-HYDERABAD
5.32
internal values like reference ype,
count
Example It stores the
and internal representation as
Ifuser wvant demo to be accessed lor reading but not Jor string valuc,length stores a string that
structure, The TCL objobjectfield when used
feldsof the
represents a
writing the open commandis aliased in the master. Thiswill set in the string in a numerical
the file to read-only mode betore opcnin: it and then ransler context number
clecimal lypc conversion takes place (i.e. from string to
the tile descriitor. 1lhis is explained in the following code,
number) And,the
resultant binary number is stored in
proc salopen path mode permission} representation ficld. internal
: code format
technique of compiling scripts intooabyte
global demo was alsoAintroduced in TCL 8.0. Here, the TCL evalfile is
sets read only permission io the file demo EvalobjEx. The second
replaced by TCL structure argument the
is
ratherthan a string as in
setehan [open S pathrS permissions] pointerto TCL obË
function.
TCL Eval
Transters the tfile
the firstt time itt will be
interp transler ( $ t demo When the script is used for stored
into byte code
After the script is compiled
return St in storedfield.
it isstring format
in, internal representation field. When TCL Evalobj
bytecode version of
Ex function is called again then TCL ERROR the script
demo alias open safeopen. or
will be used. It returns TCL OK
5.1.18 CInterface It stores the resultant string or error message in the To
obj structure which can be later retrieved using TCL Getobj
Q51. Explain about integrating TCL into' an existing
application. Result.
Answer : Q52. Explain about creating new Commands in c
To integrate TCL into an application, only aTCL header Answer : Model Paper-4, Q11(a)
is included and TCL createinterp must be called.
The structure of acommand procedure prior to TCL&0
# include < tcl.h>
is discussed below.
Tcl interp * int p When the TCL interpreter recognizes a C coded
command while passing then these argument words must be
passed to the C program. This is done in the same way as shell
intp =TCL_Createlnterp( )
does to pass arguments to a C command.
Above function will return a pointer to TCL Interp
structure. This return value will be passed as an arguments to In C, the command line starts with the following line.
other function to identify the interpreter that is involved. As, a main(int argc, char *argv[ ])
single application can invoke multiple interpreters.
Here, argc is the count of number of arguments and argy
Calling the Interpreter in the Earlier Versions of TCL Le., lis the pointer variable that holds the address of array of string.
Prior to TCL 8.0

TCL Eval can be invoked as soon as interpreter is setup The function will be called using value of argv[0] as its
name. The TCL procedure for the above line is as follows,
Example
type def int TCL cmd Proc (client Data client,
char scpt[ ] ="puts fwelcome students)";
result = TCL eval (intp, scpt); TCL Inter *intp,
If the interpretation is successful, then the result variable int argc,
is assigned with TCL_OK.Otherwise, the result yariable is set char *argv[0]);
to TCL ERROR.
The argc and argv in the above prototype will behave n
The intp ’ result has the pointer to the resultant string. the same way as in main
function.
There areseveralvariants on TCL Evalwhich are listed
below.
The 'second argument is the pointer value t0
interpreter.
1. TCL-Evalile:The second argument ofTCL-evalfileis
flename. If treats the contents of file as scripts. This TCL command procedure returns a value, TCL OK
or TCL ERROR
2 TCL-VarEval : An arbitrary number of string arguments
are followed by the interpreter argument. It concatenates The return value is stored in interp result similarto
TCL Eval
all strings into one string in order to evaluate it as a script.
The last argument TCL VarEval must always end with Now, let us discuss the structure of TCL command
NULL i.e., as a last argument. procedure inTCL 8.0
WARNING: Xerox/Photocopying
of this book is a
CRIMINAL act. Anyone found guilty is LIABLE to face
LEGAL proceeding
UNIT-5 TCL and Tk
5.33
In TCL8.0, TCL obj
structure hold all values, Thus, an
to
command
procedure rather than the array ofthepointers array of
to string, The
pointers to these structures are passed as arguments
(tvpe def int TCL prototypc of the procedurein TCL 8.0 is as follows,
Ocmdproc(clientData, clicnt.
TCL Interp *intp
int objl,
TCL ObË *CONST obj2[ ));
This pr0Cedure aIso returns TCL OK or TCL ERROR The
structure. T L set obi result is used to set the result as a 1G
This result can be later
retrieved using TCL
Registering a new Command in the Version GetObjResult.
Prior to TCL 8.0
The TCL Create command function is used to register a new eommand with the
They are as follows, internreter. This command takes 5 arguments
1. Aponter to the interpreter. This is used to register the command. This pointer is passed to
it is called. the command proceuue
The commånd's name that is used in TCL.
3 The C command procedure's name that
implements the command.
4 Theclient data i.e., client. It is passed as first argument to the command procedure when it is
called.
*The client isdata argument is used if a single command procedure is used to implement a number of commands. Each
command registered to identify that it belongs to particular family.
5 The 'delete' procedure.
The delete procedure is called when the TCL command is deleted using TCL Delete command.
Example: TCL_createCommand interp, "wibble". wibble Cmd(ind, (client)NULL,
(TCL (CmdDeleteProc*)NULL);
Here, the TCL command "wibble" is added, And, a command procedur inc is written to implement it.
Registering a New Command in the Latest TLC Version 8.0
The registration of a new commandin TCL 8.0 is similar to the registration in previous versions except that it is registered
using TCL createObjCommand rather than the TCL_CreateCommand.
Q53. Write short notes on dynamically loadable packages.
Answer :
In C, packages are defined by creating a shared library which is loaded dynamically.
Example
In response to a package require command.
'makewib' the following code is written
To create a package named 'wib' that provides TCL command
/*wib.c*/
# include < tcl.h>
/*Declaring command procedures and functions*/
int makewibemb (clientData cd,
TCL*nterp* tip, int objl,
TCL obj * CONST obj2[ ]);
*loading the package*/
int wib Init (TCLInterp*tip)

TCL_CreateObjCommand (tip,"*"wib_a",
makewibcmb, (cd)NULL,
(TCL_cmdDeleteproc*)NULL);
TCL Pkg (tip, "wib", 1.0);
return TCL OK;

sPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS


5.34 SCRIPTINGLANGUAGES rJNTU-HYDERABAD
After compilation, the compiled package is placed inthe
Pkg mklndex is run in the directory, NoW
directory.
The index cntries will be created. When the compiler
reads the following
package tequire wib.
This calls the wib Int funetion for creating a
new command.
"a
Fnaly, the TCL_PkgProvide function which will create the Pke Index.(cl file. This file is reterred by the autoleader w
command detined in this package is Used for the first time.
5.2 Tk (ToolKit)
5.2.I Tk-Visual Toolkits
Q54. Discuss the role of visual toolkits in application
programming.
OR
Write a short note on T-visual toolkits.
Answer :
(Model Paper-li, Q11(b) |April-14(R09), OB
Visual Toolkits

Visual toolkits has an important role in application prográmming, Implementation of visual interfaces is possible with
orary of tunctions that implement building blocks like menus, butons, dialog boxes etc. It is difficult to perform low-eel
programming of visual interfaces because each and every pixel on the screen has to be defined. The operating system offers an
abstraction at a simple level which is far away from pixels. Even with this simple level abstraction the developer 's programming
is at a level which is very low.
After the creation of any application the programmer has to include additional coding, so that the application can respond
to the external evernts given by the u_er. This is possible if high level abstraction is preferred. For this, X Window system and
Microsoft windows provide toolkits consisting of 'building bricks' to construct visual interfaces. Such building bricks are called
as 'widgets' in X window system and controls' in Microsoft windows toolkits and widgets are an
improvement in the level of
programming but its implementation is complex. The developers must be proficient in Cor Ct+ and must have theknowledge
of the operating system that is currently in use so as to handle the external events well.

5.2.2 Fundamental Conceptsof Tk


Q55. Tabulate the important widget classes.
Answer :
Model Paper-1, Q11(b)
Important widget classes and their functionality is tabulated below,
Widget Class Functionality
Label It is a frame containing one-line text
Frame It is a rectangular container that hold widgets
Entry It is a box used to enter a text that can be edited later

Message It is a frame holding multi-lines text


Button It is a label that responds to mouse clicks.
Listbox It is a box that displays multiple-lines of text and enables the user to select any one line
at any instant
Scrollbar It js a bar that interacts with other
widgets to identify what actually is displayed.
Text It is a widget that enables editing and displaying of
multiple-lines of text
It isa containr that holds images or
Canvas something that has be drawn into it.
t is awidget that includes
Menu drop-down menus, pop-up menus and cascading menus.
It is used to drag a pointer either
Scale horizontally or vertically tp change the integral value.
WARNING: Xerox/Photocopying of this book Sa okiMINAL aot. Anyone tOund guilty is LIABLE to face | EGAL Droceedings.
UNIT-5 TCL and Tk 5.35
056. Nrite short notes on,
File Edit
(a) Widget names
(b) Widget creation
OK
(c) Widget properties
(d) Widget hierarchies
Answer: Figure: Nesting of Widgets
(a) Widget Names Window
Widget name is the name of the widget that is given soon
Menu bar,
Menu
"after its creation. It must be unique among all the other widgets.
I must lie in the same level in the hierarchy.
Client
b Widget Creation
Dialogue box
Just by giving the widget class name one can create an
instance of the class. The widget name itself is a command. OK
Scrolbar
Example: frame .fr creates an instance of a frame named fr Figure: Widget Naming Hierarchy
The names following the dot must begin with lower-case Hence, the fully qualified name of the OK button is
.clientspace.dialog.Okbutton.
(C) Widget Properties
Q57. List the three types of geometry managers and
. Widget properties are set as soon as the widgets are cre the commands by which they are called.
ated. The properties signify the appearance of the widgets like Answer :
its colour., font size etc. Many widgets have common properties Geometry manager is the controller of the widgets p0
like size, colour, orientation and appearance. The properties can sitioning. It places the widgets within aframe. One widget can
be changed accordingly. After the creation of a widget, a com be controlled by only one geometry manager. But the geometry
mand with same name is defined instantly for the modification manager has the capability to control many widgets in a frame.
of the properties later. The instant creation of thecommand with Therefore different geometry managers can control different
same name is shown below, frames. TK provides the following three kinds of geometry
managers,
frame.fr-text Go (a) Pack
It is a constraint-based geometry manager. The con
straints are from the user's side based on the pösition of the
.ff configure -text stop widgets. For example, stacking of the widget either horizontally
(d) Widget Hierarchies or vertically. After the position has been specified the geometry
manager has to select an appropriate location for placement of
Hierarchy is formed from the widgets that build up on the widget.
interface. It is represented in the same way how file systerm paths (b) Grid
are represented with this representation a fully qualified name It allows the placement of widgets on the grid with
bcates the correct location of the named widget. The hierarchy rows and columns of different size. The rows and columns are
is top-level window-based i.e., main window ofthe application. specified by the user and the size is adjusted by the geometry
It is created as soon as the TK application initiates by calling manager inorder to fit the widget in the grid.
he TK Main function fron the C program of the application. (c) Place
The main function will develop the main window and initial
It allows the accurate positioning of the widgets by
zes vatious possible things. Then it calls TK Mainloop and means of absolute or relative x and y coordinates.
nitiates the event loop. The top-level window is an implicit
Irame, whose namne is followed by a dot "'successive levels The above three geometry managers are called by pack,
nthe hierarchy are represented by successive dots. Consider grid and place commands that accepts list of widgets, as an ar
he hierarchy below, gument along with options. The list of widgets and the options
are responsible for fine tuning the position.
SPECTRUM ALL-IN-ONE J0URNAL FOR ENGINEERING STUDENTS
5.36 SCRIPTING LANGUAGES [JNTU-HYDERABAD)
5.2.3 Tk by Example Q59. Give an example of entry widgets using pact
and grid geometry managers.
Q58. Give an example of simple button using pack Answer :
and grid geometry managers also give the us
age of timer events. Bntry wideet is a box wherein a single line text can ha
Answer : typcd and cdited. The entry command specifies a 'text varjablay
option that specifies the text to be written in the widget. Th
ln Tk, atler the widget has been ereated, a command entry commands also have the options to set the width and the
with the same nanme is detined automatically to configure the appearance. There are Actions that use "bind" command thas
widget later. ln the creation of' asimple button widget, a button accepts widget name, the underlying action and a call back scrint
is created generating an intertace specifying a proper label for it. as arguments inorder to link to the Action.
lhe most commonuse ofabutton is to click it. So, it include a
Command option with a script that executes after the button has Consider the following example of a visual front-end
enclicked, atler the button click the configure option changes phonebook. On entering the userid and pressing Return displavs
the tent onthe button. Consider the following code below, the phone number that matches with that userid. Consider tha
button .b -text "SUBMIT" \ following code toset up the visual interface.
-command {. b configure -text OK"} Label .11 - text "Username:"
Pack .b entry .el width 15 -relief sunken
The above code generats an interface with a label - text variable euname
"SUBMIT". This is shown in the following figure, label .12 text PhoneNo:"»
WINDOW
entry .e2 - width 15 relief sunken \
SUBMIT - text variable ephnno
button.. text OK command OK
Figure: Button before Clicking
pack .11 .el .12 \
After the button has been clicked the configure option
changes the label on the button formn "SUBMIT" to "OK". The .e2 .Ok - side top - pady 2
script for this operation is written in the "Command" option.
The following figure shows the mouse click. bind .el <Return> {set ephnno \
WINDOw [search by name $euname] }
bind .e2 <Return> {set uname \
SUBMIT [search- by - number Sephnno]}
Figure: Button after Clicking
The array from the file is set by the following procedure:
The pack geometry manager shrinks the client space set is[open {e:\ phones.text} p}
vertically to fit round the button. Like wise,the grid geometry array set phones[split [readS in nonewline] "nlt"]
manager also produces the same output of the client space
shrinking to fit the widget. The code for this as follows, The action/callback to search.by name is as follows: >
button .b -text SUBMIT"\ Proc search by_name{e 1}
command {.b configure- configure - text "OK"}
grid .b
Timer Events
global phones
Timer events can be generated using buttons. Consider if {[info exists phones(Se 1) ]}
the following example below,
button .b - text "SUBMIT" -Command
return $ phones(Sel)
.b configure - text "OK";
after 3000 {bell; exit}
else

Pack .b
3 seconds after the button click, a beep sound is heard and bell; return NO INFORMATION
the "wish" window vanishes. The after" command is returned
soon after the delayed action event is set. The terminal bell is
rung due to the bell" command.

WARNING: Xerox/Photocopying of this book is aCRIMINAL act. Anyone found guity is LIABLE to face LEGAL proceedings.
UNIT-5 TCL and Tk 5.37
The action callback to search bv number is as follows: Interaction of Listbox and Scrollbars
Proc search_by _numbere2) Scrollbar is awidgt that is added to the listbox toiew
Its entire content. The code for Srollbars in althox shown
globalphones below,

set el "NO INFORMATION isthor marks -serollkommand" seroll set


for each key[array names phones) pack marks -sde lktt

if {Sphonebook( Skey) = Sc2) sTollbar sroll -cummand marhr ew


pak sroll side lett tily
set cl Skcy; brcak
whulc igets Sm line0)
ifl Sel-"NOINFORMATIONI (hell)
fcturn S cl marks unsert cnd Sline

Tostack the widgcts vertxally fron top-toottoen gtd


ommand nccds five calls to thc grsd goomctry managct Ihus The output for the atecoxde may he esrv ted as shown
s because cvery grnd configure command begin a new fw in low,
he grid. Hencc pack command n thc visual antctfacr ipt a WISI O
eplaccd by the follow ing.
Roll oI 40
gid configurc ppady Roll no 2 $5
gnd configure c pady Roll no3 60
gnd configure pady
gnd contigure paty
gnd contigure paty
260. Give an example of listbox and explain its in Roll no |8 14
teraction with scrollbars.
Roll no 19 25
Answer : Roll no 20 S4
List Bor
The codc to creatc a sumple listbox s as follows, Figure Scrollbar in Lstbex
List bor marks Ihe solid bar in the abuvc tigue teprescnts thc lotal sice
pack marks of the listbox that is to be display cd On cuaing of dragging il
Set m (open (e marks M)1) moves the list to the des1red pusitton On clking the u artuw o
While i{gets Sm linc 0) down arrOW moves the list onc poston up o down Uc listhos
Listbox has a command option tha! >pxitic a patial
marks insert cnd Sl1nc command to be invokcd when the data in the listh change
The partialcommand c, crollsct ts tollowed hy thc argunnents
Theoutput for the above code may be cxpccted as shown given by thc listbox. 1This command redraws the wrollhar t has
elow, the following full form: widget sct first tast
WISH 20 E Irst and last acccpts tloat1ng pont valucs hetween 0
Roll o1 40 and 1.They give thc relat1ve position of the data or the clement
Roll o 55 that is to be displaycd if the clemcnts in the lsthovchange, it
Rol o 3 calculates new valucs for first and last to append them to the
Roll o 4 scroll set command This dsplay s the sctollhat again with a
solid block in its cxact position
Roll o 10 Serollbar has a command opton that peifies a partial
Figure: List Box command to bc invokcd when the scrolihar is being clhched or
dragged marks yvicw is the partial command that changes the
Since the default size of the lstbox is 10, only the irst data in the listbox by scrolling it to some appropriate units. Ih
O
elements are visible. The while loop in the above code reads fullformn of this command is widget yview scroll num untts
ne line at a time from the file "marks". It inserts this linein the Scroll1ng is upwards if num valuc Is negative othewie it i
ariable line. Then, this line is inserted in listbox marks downwards.
SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS
SCRIPTING LANGUAGES [JNTU-HYDERABAD]
5.38
(c) Mouse Events
If grid command is used then the widgets get placed in
the centre of the window to create a layout of ono row and two These are several mouse events which are given
columns use the following command, follows,
grid configure .listbOX .seroll Mouse Pressed Mouse was pressed
The size of the serollbar is set to default unless it is Mouse Release Mouse was released
2.
specitied. Using the option sticky the widget is placed on the Mouse wheel Mouse wheel was moved
specifiedplace on tlhe screen.Along with-sticky if theoptions 3.

n, s, eor w is used then the widget is aligned along the edge 4. Mouse entered Mouse entered a component.
that is spccified for its cell in the grid. On using the options ns 5 Mouse leave Mouse exited from acomponent.
or ew the widget is stretched to the edges specified. This can
be written as grid configure .listbox .scroll - sticky ns. Syntax
5.2.4 Events and Binding bind .w <Button -1> {------}
Q61. Write a short note on events and bindings. Q63 Explain events and its usage in Tk with examples.
Answer : (Model Paper-ll, Q11(a) | Dec.-14(R09), Q6(b)) May-13(R09), Q6
Answer
ver :

Events Events ánd its Usage in Tk


For answer refer Unit-V, Q62.
For answer refer Unit-V, Q62.
Binding
Example
For answer refer Unit-V, Q64.
import Tkinter from Tkinter import*
Q62. Write short notes on,
root= Tk()
(a) Events
(b) Keyboard events prompt = "press any key, or click any button'
(c) Mouse events l= label (root, txt =prompt, width = length(prompt)
Answer : l.pack( )
(a) Events def key(event1 ):
An event is an action performed by the user. In the if eventl.char == event1.keysym:
delegation event model, an event is an object that shows astatus message="These are normal keys or%% eventl.char
i.e., state changes in a source. Events are generated when the user
interacts with the elements in a graphical user interface. Some of elsiflength(eventl.char) =1:
the actions that generate events are pressing a button, entering message =These are punctuation keys %or (%r)'
the data via keyboard, selecting an item in a list, clicking the % (event1.keysym,event1.char)
mouse etc. These are all the events that are generated by a user else:
by interacting with a user interface.
message =These are special keys %r %event1.keysym
Events may also be generated without interacting with
user interface. For example, an event may be generated when the 1.config(text=message)
timer expires, a counter reaches a value, a software or hardware 1.bind-all(»<key>' key)
failure occurs, or an operation is completed. def do-mouse(event _name):
Syntax def.mouse-bind (eventl ):
bind .w <Button - 1> {------}
message = "Generated mouse event is %s' event name
bind .w <key-space> f----}
l.config (text.message)
(b) Keyboard Events
1.bind-all (<%s>' event name, mouse bind)
Whenever a key is pressed or Released, keyboard events
are generated with the help of keyboard events, we can control for iin range (1, 3):
and perform actions or get input from the keyboard. do-mouse ('Button pressed-%s %i)
Syntax do-mouse ('Button released-%s' %i)
bind .b <keyPress - x) {--} . do-mouae (DoubleButton pressed -% s o
bind .b <keyRclease - x> {----} root.mainloop( )
WARNING: Xerox/Photocopying of this book is aCRIMINAL act. Anyone found guilty is LIABLÈ.to face LEGAL proceedings.
UNIT-5 TCL and Tk 5.39

Q64. Explain briefly about the "bind" command.


Answer :
Bind Command
The bind command is used to register a callback script which has to be executed on the occurrence of one or more events
in one or more specified windows. This list of windows is called tag.
Syntax
bind tag sequence script
Here, tag defines in which widget the event has to be recognized, the sequence defines the actions of theuser by which
the events raise and the script is an arbitrary TCL script which is being protected by the braces from immediate evaluation. The
seript willbe added to the existing bindings for the tag ifit is preceded by a+. Otherwise, the existing binding will be replaced
by it. Anull script {} can be specified to remove a binding.
Q65. Explain with an example how Tk is used for implementing event driven programs.
Answer :
Dec.-14(RO9), Q6(a)
Event driven programs suggest the procedure for how to design the programs control flow. This again consist of certain
actions such as reacting to the external events. These programs can make use of co-toutines, threads, generators etc., in order to
process the external events. Event processing facilities in Tk are provided by commands such as bind and event.
For remaining answer refer Unit-V, Q62,Q64.
Q66. What does the event "generate" command do? Explain about virtual events.
Answer :
Event Generate Command
The évent generate comnand allows an event to be processed as if the operating systenm has reported it to do.
Syntax
Event generate .b <Button-1>
The piece of code enables the event handler to be invoked fora mouse click on b(button) as if the user has actually clicked
the button. It does not allow sequences and allows event specification to be single event.
Virtual Events
A virtual event is an event which is associatd with multiple event sequences. It fires on the occurance of one of these
sequences. For example, avirtual 'paste' event can be created in awindows application which will fire on ctri -v or shift-insert
event add <<paste>><control-key-v>kshift-key-insert> virtual events use double angle brackets. It can be used in a bind command
like other events.
Bind entry <<paste>> (%w insert [selection get]}
It can be raised by the event generate command in a script.
Q67. Write about callback scripts.
Answer :

Callback Scripts
The callback is'a Tcl script, which is protected by the braces from being evaluated. It is nothing but a call of
a procedure
which defined some where else. Th» special variables which represent the attribute information which are
related to an event
can be accessed by this seript. Hence, %b, %X and %y contain the.button number and the
mnouse
mouse events at the time of the event. The %w contains the widgl name for all the events. For coordinates respectively for the
example, the commands to turn
the button red when the mouse enters and restore the dfault color when it leaves would be,
bind Button <enter> {%w configurel- background red}
bind Button <LEAVE> {%wconfigure- background grey}
We can add the arguments inorder to provide the information to be
returned in the percent' variables if at all an event is
raised in the script with event generate.
event generate . f <Button -1>-x 10- y20
Here, .fis frame which generates the mouseclick event at (10, 20) coordinates. These values will be
callback script gets evaluated. So, they can be used as procedurE substituted before the
arguments.
bind Button <Button - 1> {btnl click w}

SPECTRUMALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS


SCRIPTING LANGUAGES rJNTU-HYDERABAD)
5.40

5.2.5 PERLTk
Q68, What is Perl-toolkits? Explain how it is difforent from Tcl/Tk.
Answer :
Model Paper-ill, Q11b)
Perl-Tk
Pel-Ik ovides the lk funetionality in perl cnvironment allowing it to add GUIto Perl script. It is designed in such a

way that a novice uNeT ot it who is familiar with Tel/Tk can quickly adapl.
Difference Between Perl-Tk and Tel/Tk
Tcl-Tk
Perl-Tk
TCL-Tk is a command language which js written in TCL
Perl-Tk provides the Tk functionality in perl 1.
procedures
environment allowing to add GUI to Perl script. and built on-the-fly commands and
It allows the user to create and manipulate the
It implements the widgets as objects by using 2
which are group of visual
items. widgets
a group of methods.
3 It uses the event and the call back script as 3 It uses the name of the widget, the event and the call
arguments in order to invoke the widget's bind back script as arguments along with the bind command
callback
method. in order to associate an event with a
4. Example 4. Example
button .b -text "press Me". \ command fexit} Smw = new Mainwindow;
Pack .b $b = $mw -’ Button (-text ’ "Press Me",
- command ’ sub fexit})’ pack;
Main Loop;

WARNING: Xerox/Photocopying f this booOK IS a CKIMINAL act.


Anyone found guilty is LIABLE to face LEGAL proceeu
UNIT-5 TCL and Tk
5.41

IMPORTANT QUESTIONS)
SHORT QUESTIONS
Q1. Write a short notes on TCL.
snS: For answer refer Unit-V, O1.
Important Question
Q2. Write a short notes on patterD matching
using regular expression.
Ans: For answer refer Unit-V, 03.
Important Question
Q3. Write about eval command.
Ans: For answer refer Unit-V, 04.
Important Question
04. Discuss in brief about server sockets.
Ans: For answer refer Unit-V, Qs.
Important Question
Q5. Write a short note on visual toolkits.

Ans: For answer refer Unit-V, Q7. Important Question


Q6. Write short notes on Events.
Ans: For answer refer Unit-V, 09. Important Question

ESSAY QUESTIONS
Q7. Explain the structure of TCL.
Ans: For answer refer Unit-V, Þ13. Important Question

Q8. Describe the syntax of TCL.


Ans: For answer refer Unit-V, Q14. Important Question

Q9. Define TCL structure.Give a brief note on examples of parsing.


Ans: For answer refer Unit-V, Q17. (Important Question | Dec.-14(RO9), Q5(a)
Q10. Explain the "if" and "switch" commands.
Ans:. For answer refer Unit-V, Q19. Important Question

Q11. Explain the list data structure in TCL with a sample code.
Ans: For answer refer Unit-V, Q22. (Important Question|May-13(RO9), Q5(a)
Q12. Explain about producers.
Ans: For answer refer Unit-V, Q24. Important Question

Q13. Explain _tring operations with suitable examples.


Ans: For answer refer Unit-V, Q30. Important Question

Q14. Explain the following commands,


a) eval
(b) uplevel.
Important Question
Ans: For answer refer Unit-V, Q35.

SPECTRUM ALL-IN-ONE JOURNAL FOR ENGINEERING STUDENTS


SCRIPTING LANGUAGES
5.42

Q15. Discuss briefly about namespace in TCL.


rJNTU-HYDERABAN
(Important Question |April-14(RO9),
Ans: For answer refer Unit-V, Q39.
Q16. Explain the concept of event driven programming.
(Important Question April-14RO9),
Ans: For answer refer Unit-V, Q43.
Q17. Write the nuts and bolts of internet programming.
Ans: For answer refer Unit-V, Q45. (Important Question | Dec.-14(R09), Q5(b) | May-13(RO9), ds.

Q18. Explain events and its usage in Tk with examples.


(Important Question |
Ans: For answer refer Unit-V, Q63.
Q19. What is Perl-toolkits? Explain how it is different from Tcl/Tk.
May--13(R09),
Ans: For answer refer Unit-V, 068. Important Questo

WARNING: Xerox/Photocopying of this boOK IS a


CKIMINAL act. Anyone found guilty is LIABLE o face
LEAL Droceedings

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy