Custom Commands
Also known as procedure.
proc procName {list_of_params} {
## Procedure body
}
Invoke-
procName [ args ... ]
Do not use parenthesis around args while invoking a procedure, since it is a command not a function.
Return variable is optional in procedure definition
In face, return command is also optional.
Example:
% proc message {} {
puts "Inside message proc."
}
% message
Inside message proc.
* Local variables defined inside a procedure are accessible only to that procedure.
* Variables defined outside the procedure cannot be accessed directly by the procedure.
Default arguments:
% proc message { {a 1} {b 2} } {
puts "Inside message proc with a=$a, b=$b"
}
% message
Inside message proc with a=1, b=2
% message 4
Inside message proc with a=4, b=2
% message 5 6
Inside message proc with a=5, b=6
To access variables defined in script inside a procedure use global:
proc add {} {
global a b
return a+b
}
set a 4
set b 1
puts [ add ]
5
To access variables defined inside caller procedure:
proc proc3 {} {
upvar 1 x w y v z u
upvar 2 b z
puts "Inside proc3: Values from proc2 x=$w y=$v z=$u"
puts "Inside proc3: Values from proc1 b=$z"
}
proc proc2 {} {
upvar 1 a x b y
upvar 2 b z
puts "Inside proc2: Values from proc1 a=$x b=$y"
puts "Inside proc2: Values from script b=$z"
set x 12
set y 17
set z 22
proc3
proc3
}
proc proc1 {} {set a 100
set b 99
proc2
}
set b 20
proc1
Inside proc2: Values from proc1 a=100 b=99
Inside proc2: Values from script b=20
Inside proc3: Values from proc2 x=12 y=17 z=22
Inside proc3: Values from proc1 b=99
« Previous Next »
Comments
Post a Comment