Você está na página 1de 11

TCL & OTCL

Programming

TCL Introduction
Tcl is a general purpose scripting language.
While it can do anything other languages could possibly do, its
integration with other languages has proven even more powerful.
The strength of Tcl is
Simplicity
It is not necessary to declare a data type for variable prior to the
usage.
At runtime, Tcl interprets the codes line by line and converts the
string into appropriate data type (e.g., integer).
Execution of Tcl file

If you write some code to a file- create tcl file as given bellow.
Name of the file. Extension (tcl)

"hello.tcl"
you want to execute it, you would do it like so:
tclsh hello.tcl
Directly In Console
Type "tclsh" in the console.
Type tcl code into console.
Give enter to get result.

Points to be considered for writing TCL script


Comments
A command in Tcl is a list of words terminated by a semicolon. Tcl comments
are a # at the beginning of the line, or after the command is closed with
a; semicolon.
This is a comment after the command.
set a 22 # same thing?
set a 22 ;# same thing

<- Wrong!
<- OK

Everything is a command
Everything in Tcl is a command followed by a number of arguments, which
are separated by whitespace.
PUTS
Puts command that takes only two arguments.
% puts stdout Hello
Hello
stdout- output stream
The output stream argument is optional for puts and if not included it
defaults to stdout.

Hello-what should be printed to that output stream?

Lets say we want to print Hello World instead of Just Hello.


% puts stdout Hello World
bad argument "World"
This results in an error.
OTcl is treating World as third arguments to the puts command.
Hello World to be a single argument.

To do that, we need to use a concept called grouping. Grouping can


be done using either double quotes or brackets.
% puts stdout "Hello World"
Hello World
% puts stdout {Hello World}
Hello World
VARIABLES
% set x 5
5
First is the name of the variable and the second is the value you want to
store in the variable.
% set y Hello
Hello
% set z {Hello World}
Hello World
A command unset is used to clear the value stored in a variable.
% unset z
% puts $z
Cant read "z": no such variable even dont assign zero
To access the value of a variable $ symbol is used before.
% puts $x
5
% puts $y
Hello
% puts $z
Hello World
% puts y
y
EXPR
It takes a variable number of arguments, concatenates them together,
then evaluates the result Priority ()*/%+-

% expr 3+2*5
13
% expr (3+2)*5
25
BRACKETING
We want to print the result of the expr command.
% puts expr 6 * 7

wrong # args

[ ]: evaluate command inside bracketsit interpret the string in a


square bracket before interpreting the entire line.
% puts [expr 6*7]
42
% set answer [expr 6 * 7]
42
We really want to do is first evaluate the expr command. To do
this, we wrap the command with square brackets in OTcl.
"": The double quotes allow for substitution,
{}: The curly braces do not allow for substitution.
%
x
%
x

puts "x is $x"


is 5
puts {x is $x}
is $x

(): Parentheses for indexing an array and for invoking built in


mathematical functions.
EVALUATING AND DEFINING COMMANDS
Procedures or functions
Use the proc command to define a Tcl procedure (known as a
subroutine or function in other scripting and programming languages).
Use the return command to return the value from the procedure.
Shows how to use the multiply procedure in your code. You must define
a procedure before your script calls it

proc sub1 x {expr $x-1}


Here sub1: name, x: list of argument names, {expr $x-1}: body of the
procedurein single line.
Example: Using a Procedurefunction with arguments and return value.
proc multiply { x y } {
set product [expr { $x * $y }]
return $product
}
set a 1
set b 2
puts [multiply $a $b]
ARRAY
An array is a special variable which can be used to store a collection of
items.
An array stores both the indexes and the values as strings.
You do not need to define the size of the array like you would in other
programming languages.
The indexes for the array are also not restricted to integers like most
languages.
String indexes
%set wlan(protocol) tcp
tcp
Numeric indexes
% set arr(0) 30
30
% set arr(1) 50
50
% puts $arr(1)
50
% set arr("something") 99

% set x 0
0
% puts $arr($x)
30
If we wanted to get the length of the array, we can issue the following
command.
% set length [array size arr]
start from 0
The array set command requires a list of index/value pairs. This
example sets the array called days:
array set days { Sun Sunday Mon Monday Tue Tuesday \
Wed Wednesday Thu Thursday Fri Friday Sat Saturday}
CONTROL STRUCTURES
Tcl comes with a number of built in commands for control structures
If/else
1
2
3
4
5
6

set x 5
if { $x == 1 } {
puts Not true
} else {
puts True
}
The following will give you an error.

1
2
3
4
5

set x 5
if { $x == 5 }
{
puts True
}
This is because the if command takes at least two arguments: the
condition and the body.
In the above example, one of the arguments is a newline character.

You have to put the close bracket and open bracket between
arguments on the same line. (This is similar to what we saw earlier
when defining new commands with proc).
If/else if statements
1
2
3
4
5
6
7

if { $x == 1 } {
puts first
} else if { $x == 2 } {
puts second
} else {
puts third
}

While loop
The while command takes two arguments. The first is a condition it will
check on each iteration and the second is the body of the loop.
1
2
3
4
5
6
7

set value 1
set fact 2
while { $ fact <= 5 } {
set value [expr $ v a l u e $ fact ]
incr fact
}
puts $ value

For loop
The first argument to the for command is assigned once.
The second is checked after each iteration,
The third is executed after each iteration, and the last argument is the
body of the loop.
1
2
3
4
5

set sum 0
for { set i 0 } { $ i < 10 } { incr i } {
set sum [ expr $sum + $ i ]
}
puts $sum

For each Loop


foreach loop to print each element in a list
set a { 1 2 3 }
foreach element $a {
puts "The list element is $element"
}
GLOBAL VARIABLES
Global variables are common and used extensively throughout a
program.
These variables can be called upon by any procedure in the program.
set PI 3.1415926536
proc perimeter {radius} {
global PI
expr 2*$PI*$radius
}

PI is defined outside of the procedure perimeter

The command global is used here to make PI global and


available within the procedure.

LISTS
A list is an ordered collection of elements such as numbers, strings or
even lists themselves. Arrays are similar to lists except that they use a
string-based index.
Creating Simple Lists
(i) % set a "1 2 3"
123
(ii) % set a {1 2 3}
123
lindex command - Retrieve an element from a list
% lindex $a 2
3

llength command - Returns the length of a list


% llength $a
3
lappend command - appends elements to a list.
% lappend a
1

4
5

FILE I/O
Tcl includes commands to read from and write to files.
First you must open a file before you can read from or write to it, and
close it when the read and write operations are done.
To open a file, use the open command; to close a file, use the close
command.
When you open a file, specify its name and the mode in which to open
it.
If you do not specify a mode, Tcl defaults to read mode.
To write to a file, specify w for write mode
set nf [open out.nam w]
set f [open out.tr w]
You can use the puts command to write into a file
Example: Write to a File
set output [open myfile.txt w]
puts $output "This text is written to the file."
close $output
You can read a file one line at a time with the gets command.

Example: Read a File


You can read a file one line at a time with the gets command. Example uses
the gets command to read each line of the file and then prints it out with its
line number .
set input [open myfile.txt]
set line_num 1
while { [gets $input line] >= 0 } {
# Process the line of text here
puts "$line_num: $line"
incr line_num
}
close $input
OTcl -OBJECTED ORIENTED TCL
OTcl Version of TCL
In OTcl, important- the concepts of classes and objects.
A class is a representation of a group of objects-which share the same
behaviours.
Such behaviour can be passed down to the child (parent (superclass) to
child (sub class)).
This inheritance is also very important concept.
Class and inheritance
To declare the class, we first give keyword class then give its classname
Class classname superclass superclassname
Example: Network node
Main class: class node
Child class: mobile
Class mobile inherit the capabilities of class node
Class Node
Class mobile-Super class node

Class Member Procedures and Variables


A class can be associated with procedures and variables.
In OTcl, a procedure and a variable associated with a class are referred
to as instance procedure (i.e., instproc) and an instance variable (i.e.,
instvar), respectively.
Instance Procedures
Defining functions of the class is just like defining commands instead of
proc you use<classname> instproc <procname>
Syntax
<classname> instproc <procname> [{args}] {
<body>
}
Instance Variables
Classes can have instance variables that are accessed through the self
variable.
All functions of the class have access to any instance variables.
Syntax for the declaration
$self instvar <varname1> [<varname2> ...]

Você também pode gostar