ID 683432
Date 12/13/2021
Public

## 2.9.8. Procedures

Use the proc command to define a Tcl procedure (known as a subroutine or function in other scripting and programming languages). The scope of variables in a procedure is local to the procedure. If the procedure returns a value, use the return command to return the value from the procedure. The following example defines a procedure that multiplies two numbers and returns the result.

### Simple Procedure

proc multiply { x y } {
set product [expr { $x *$y }]
return $product } The following example shows how to use the multiply procedure in your code. You must define a procedure before your script calls it. ### Using a Procedure proc multiply { x y } { set product [expr {$x * $y }] return$product
}
set a 1
set b 2
puts [multiply $a$b]

Define procedures near the beginning of a script. If you want to access global variables in a procedure, use the global command in each procedure that uses a global variable.

### Accessing Global Variables

proc print_global_list_element { i } {
global my_data
puts "The list element at index $i is [lindex$my_data \$i]"
}
set my_data { 1 2 3}
print_global_list_element 0