Tcl/Tk Programming
In this
post, you may learn
·
To know the basics of Tcl/TK Programming
·
To create a Tcl script
Tcl
Programming
Over the span of 25 years a simple modular scripting language was developed and modified or improved by corporates, academia, open source community and web developers. The code developed and the binary source is free with no strings attached. This is one of the oldest scripting language still being used for testing the network equipment like routers, switches, etc. And used in electronic IC designs and used as a front end tool (testing tool) for Network Simulator 2 (NS2).
Tcl was created by John Ousterhout mainly for embedded system applications for its ability for rapid prototyping, scripted applications and also fir its small or bigger footprints.
3.1 Features of Tcl/Tk
Rapid Development: Tcl almost runs 5 to 10X faster than other scripting languages if it involves GUI, string handling or integration.
Graphical User Interface Using its Tk toolkit, Tcl provides facilities for creating GUIs that are incredibly simple yet remarkably powerful.
Cross Platform Tcl/Tk runs almost same on all operating systems like Windows, Macintosh, and Linux/Unix platform.
Continuous upgrades: Since 1990s Tcl and Tk have been under continuous and rapid upgrades which makes Tcl/Tk really a reliable and solid scripting language that can be relied upon.
Deployment Tcl can be deployed as a single application on a target machine very easily whereas other dynamic languages makes deployment harder.
Network-aware applications: Tcl has a wide number of event driven codes that are helpful in generating events for networked devices like routers, switches, routing extensions, etc.
Apart from
these features, Tcl also has a vibrant Community that helps developers with
provision of free extensions, plugins and updates. Also Tcl is easy to learn
and all these come free. Tcl/Tk is completely free with even the binary source
can also be modified or upgraded.
3.2 Tcl interpreter and Execution
Tcl scripts
are usually having extension of .tcl and can be executed using tclsh or wish. In Linux/Unix families,
following is the way to interpret the tcl scripts.
# tclsh filename.tcl
The command
wish will be working for GUI and text mode. Sometimes tclsh can be coming along
with version number for example tclsh86.exe
and can be executed as follows
C:/> tclsh86 filename.tcl
C:/> source filename.tcl
Here is the
screenshot of tclsh.
tclsh interpreter |
Since this book is related to Network Simulator 2 (NS2), the commands and the syntax in this chapter will be related to NS2 and its simulation libraries. However for the understanding of new developers, bits and pieces of the tcl scripts are presented.
3.3 Getting Started
Let us go through some basic syntax of Tcl Programming. The following examples will give you a general introduction for Tcl Programming.
The syntax of Tcl is not similar to C or C++, rather it is simple and straightforward. This chapter will give you a glimpse of the Tcl syntax used in NS2
Example 1: “Hello World”
# This is an example to demonstrate the Hello World
puts “Hello World!”;
#printing Hello World! to the screen
To run this file, tclsh
ex1.tcl, if the operating system is windows then tclsh.exe ex1.tcl.
● puts
is the command to print anything to screen
● if
comments are to be placed at the end of the statement, then a trailing semi
colon is a must, as shown in the example above.
● A
comment always starts with a preceding # symbol.
3.3.1 Basic syntax
Tcl scripts are full of commands separated by newlines. A typical
example of Command is given below.
expr 3 + 10
This command computes the sum of 3 and 10 and returns the result, 13. You can try out this example using tclsh.
There are different words that are separated by space.
There are four words in this example: expr
,
3
, +
,
and 10
. The expr
command is an arithmetic expression,
computes the result of that expression, and returns the result as a string.
Sometimes the same above command can also be represented as
expr 3+10
All commands returns results, even if a command has no results to display, it displays a empty string.
3.3.2 Assigning values to Variables
In Tcl, everything is represented as string, but
internally it also represents integers, double, list or some other types. This
enables faster interpretation.
For this, the assignment command is used in Tcl which
is set
. When the set command is dealing with two arguments
as in:
set name TclTk
the (name) in the first command references which stores TclTk in the memory. Set command always returns the contents of the variable named in the first argument. So in this command, TclTk without quotes is being stored in the memory which is referenced by the (name) in the first command.
Set
can
also be invoked with only one argument. When called with just one argument, it
will return the contents of that argument.
Here's a summary of the set
command.
set
variableName valueOfVariable
If valueOfVariable
is specified, then the contents of the variable variableName
are set equal to valueOfVariable. (Like the example we have
seen above)
If variableName
consists only of alphanumeric characters, and no parentheses, it
is a scalar variable.
If variableName
has the form variableName
(index)
, it is a member of an associative array.
Example 2: “Variable and Values”
set Name “I am Tcl”
set A 10
puts $A
puts $Name
set label "The value in A is: "
puts "$label $A"
3.3.3 Command substitution
Command substitution is a important concept in Tcl
where result of one command argument can be used for another command. Here is
an example
set a 25
set b [expr $a*4]
When a [
appears in a command, Tcl treats
everything between it and the matching ]
as a nested Tcl command. Tcl evaluates
the entire expr $a*4 as a single command and substitutes as a separate command
and another command set b will be holding the value 100. For future reference,
b can used as $b.
3.3.4 Quotes and braces
For example,
consider the following script:
set x 10
set y 20
set z "$x + $y is [expr $x + $y]"
The
value of z after the evaluation is 10+ 20 is 30
. Everything command
between the double quotes is passed to the set
command as a single word. Note that a
command and variable substitutions are performed on the text between the quotes;
and the quotes themselves are not passed to the command. If the quotes in the
above example were absent, the set
command would have received 6
arguments, which would be an error.
Curly braces provide another way of grouping information into words.
They are different from quotes in that no substitutions are performed on the
text between the curly braces:
set z {$x + $y is [expr $x + $y]}
This command sets variablez
to the value "$x + $y is [expr $x + $y]
".
3.3.5 Looping and Control structures
Tcl provides almost all the control structures that were available with
other programming languages. Tcl control structures are commands that take Tcl
scripts as arguments.
if statements
if { test1 } {
body…..1
} elseif { test2 } {
Body…..2
} else {
Body….n
}
Example 3: Simple Example using if
puts "What’s your mark in Scripting
Language"
gets stdin marks
if {$marks > 90} {
puts
"Great, you got S Grade"
} elseif {$marks > 50 && $marks < 90} {
puts
"Hey You passed the Exam"
} else {
puts
"You need to improve your marks next time"
}
This code gives a simple example of if statement with conditional statements. This example also helps understanding that how to get the input from the user using gets stdin
For Loop
The for loop in Tcl takes the same format as of other
languages like
for { initialization }{ condition } { increment or
decrement }{
body
}
Example 4: Sum to N Terms
set x 10
set sum 0
for { set i 0 } { $i <= $x } { incr i } {
set sum [expr $sum+ $i]
}
puts $sum
The above example displays the sum of first 10 elements which is 55.
While Loop
The while loop syntax is as follows:
while { condition } {
Body of the loop
}
For example, here is a small code that helps in understanding while loops in a greater way
Example 5 – Squaring a number using while loop
set x 10
while { $x < 10 } {
puts [expr $x * $x ]
incr x
}
Like for and while, there are foreach and for…in loops are also used in Tcl programming. Since this book is being written for Network simulator 2 and its simulation objects, the readers are advised to learn more about Tcl programming in these books [1].
3.3.6 Procedures
A procedure is a block that contains series of
commands. Functions in other programming languages are preferred as Procedures in
Tcl. The Modularity of the program is maintained when procedures are used. Here
are some of the pros of the procedures:
- Reducing
the code size by avoiding duplication
- Groups
in to simpler tasks rather than complex task
- Reuse
of code
There are user defined procedures and built in procedures. The keyword proc is used to define the user defined keyword.
Example 6 – Tcl Procedure Example
proc display {} { ; #This is the line to create a procedure using
the command proc
set ns
[expr 1 + 2] ; # evaluates
the expression 1 + 2 and assign it to ns
puts
$ns ; # display the value
to the screen
}
display; #calling the procedure
the display
procedure is called using display as given in the last line of
the code. It is understood that this procedure does not contain any arguments
or parameters.
Procedure with arguments
Procedures can
also take arguments. The following examples show the procedure with single
argument.
proc hello{f}
{ ; # f is the argument here
puts “Hello Mr. $f”
}
puts [hello
“Pradeep”]
puts
[hello “Amit”]
Output.
Hello
Mr. Pradeep
Hello
Mr. Amit
Next example
with more than one argument, let us see an example to find out the biggest
among three numbers. So there can be three arguments.
proc biggest { a b c } {
if {$a > $b && $a > $c }
return $a
} elseif {$b > $a && $b > $c} {
return $b
} else {
return $c
}
set a 10
set b 20
set c 30
set val [biggest $a $b $c]
puts “The biggest of $a, $b and $c is $val”
Procedures are the powerful commands in Tcl and it is very much useful in producing reusable codes that also reduces the code size.
3.3.7 Working with Files
Like other languages, Tcl also has file handling
facility and it can open, read and write to files.
Syntax:
set nf [open file.txt w]
puts $nf “This is a simple example to write to a file
The file attribute can be
r – Open the file for reading and file should exist.
r+ - Open the file for reading and writing.
w – Open the file for writing, and if the file exists
already, it will be overwritten, else a new file will be created.
w+ - open the file for reading and writing.
a - open the file for writing. If the file already
exists, the cursor will point to the end of the file, if the file not exists, a
new file will be created.
a+ - Open the file for reading and writing. If the
file already exists, the cursor will point to the end of the file, if the file
not exists, a new file will be created.
It is always a good practice to close a file once the job is done. The following code shows how to close the file. In Tcl programming, usually all the open handles like files, pipes, any global variables, etc can be closed at the end of the program.
set tracef [open file.dat a]
puts $tracef “This is an example to show the file
close”
close $tracef
The file is opened in the append mode and if the file.dat is already existing, then the string “This is an example to show the file close” will be written to the end of the file.
Conclusion
This chapter informs the bits and pieces of Tcl
programming to a limited level. Since this book is intended for Tcl files that
are written for network simulation and hence limited information is provided
for Tcl. The readers are advised to read the full-fledged tutorial for Tcl if
they wanted to do extensive programming on Tcl.
Comments
Post a Comment