Scripting Languages U-5
Scripting Languages U-5
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
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
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{
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
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.
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
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
User User
input interface Parser
Read from
Parser
keyboard
or file
Build-in TCL
commands procedure
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.
Output set 40 X
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
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
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
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 :
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
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.
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 -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.
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"
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
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
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
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]]|
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.
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;
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.
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,
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 :
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}
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;
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.
ESSAY QUESTIONS
Q7. Explain the structure of TCL.
Ans: For answer refer Unit-V, Þ13. 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