- Tcl - Regular Expressions
- Tcl - Built-in Functions
- Tcl - Error Handling
- Tcl - File I/O
- Tcl - Namespaces
- Tcl - Packages
- Tcl - Procedures
- Tcl - Dictionary
- Tcl - Lists
- Tcl - Strings
- Tcl - Arrays
- Tcl - Loops
- Tcl - Decisions
- Tcl - Operators
- Tcl - Variables
- Tcl - Data Types
- Tcl - Commands
- Tcl - Basic Syntax
- Tcl - Special Variables
- Tcl - Environment Setup
- Tcl - Overview
- Tcl - Home
Tk Tutorial
- Tk - Geometry Manager
- Tk - Windows Manager
- Tk - Events
- Tk - Images
- Tk - Fonts
- Tk - Mega Widgets
- Tk - Canvas Widgets
- Tk - Selection Widgets
- Tk - Layout Widgets
- Tk - Basic Widgets
- Tk - Widgets Overview
- Tk - Special Variables
- Tk - Environment
- Tk - Overview
Tcl/Tk Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Tcl - Procedures
Procedures are nothing but code blocks with series of commands that provide a specific reusable functionapty. 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 imppcit 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 120Advertisements