TCL Procedures
TCL Procedures
Syntax :
body
Example :
proc helloWorld {} {
helloWorld
Hello, World!
Example :
proc fac x {
if {$x <= 1} {
return 1
}
expr $x * [fac [expr $x-1]]
}
fac 4 fac 0
⇒ 24 ⇒1
4 VIT - SENSE 10-01-2024
Procedures with multiple arguments
Example :
proc add {a b} {
40
Example :
40
110
set sum 0
65
66 VIT - SENSE
7 10-01-2024
Local and global variables
In the Tcl procedure body, all the variables assigned or passed are called local variables.
They are only accessible within the procedure and are deleted when the procedure returns.
A procedure can reference global variables with the global command using the following syntax.
The global command treats each of its arguments as the name of a global variable.
References to those names within the procedure will be directed to global variables instead of local ones.
global accumulator
accum { World}
puts "$accumulator
When the above code is executed you will get the following result.
procedure.
It can be used to access either global variables or local variables in some other active procedure.
The first argument to upvar is the name of a variable accessible to the procedure’s caller.
upvar $name a
printarray info
When the above code is executed you will get the following result.
age = 37