Tcl - Procedures


Advertisements

Procedures are nothing but code blocks with series of commands that provide a specific reusable functionality. It is used to avoid same code being repeated in multiple locations. Procedures are equivalent to the functions used in many programming languages and are made available in Tcl with the help of proc command.

The syntax of creating a simple procedure is shown below −

proc procedureName {arguments} {
   body
}

A simple example for procedure is given below −

#!/usr/bin/tclsh

proc helloWorld {} {
   puts "Hello, World!"
}
helloWorld

When the above code is executed, it produces the following result −

Hello, World!

Procedures with Multiple Arguments

An example for procedure with arguments is shown below −

#!/usr/bin/tclsh

proc add {a b} {
   return [expr $a+$b]
}
puts [add 10 30]

When the above code is executed, it produces the following result −

40

Procedures with Variable Arguments

An example for procedure with arguments is shown below −

#!/usr/bin/tclsh

proc avg {numbers} {
   set sum 0
   foreach number $numbers {
      set sum  [expr $sum + $number]
   }
   set average [expr $sum/[llength $numbers]]
   return $average
}
puts [avg {70 80 50 60}]
puts [avg {70 80 50 }]

When the above code is executed, it produces the following result −

65
66

Procedures with Default Arguments

Default arguments are used to provide default values that can be used if no value is provided. An example for procedure with default arguments, which is sometimes referred as implicit arguments is shown below −

#!/usr/bin/tclsh

proc add {a {b 100} } {
   return [expr $a+$b]
}
puts [add 10 30]
puts [add 10]

When the above code is executed, it produces the following result −

40
110

Recursive Procedures

An example for recursive procedures is shown below −

#!/usr/bin/tclsh

proc factorial {number} {
   if {$number <= 1} {
      return 1
   } 
   return [expr $number * [factorial [expr $number - 1]]]

}
puts [factorial 3]
puts [factorial 5]

When the above code is executed, it produces the following result −

6
120
Advertisements