TCL Procedures

Procedures are blocks of code that contain a sequence of commands, offering specific reusable functionality. They help avoid redundant code across multiple locations.

Procedures in Tcl are akin to functions in various programming languages. In Tcl, this is achieved using the proc command. Here’s the syntax:

Syntax:

proc procedureName {arguments} {
    body
}

Proc Command

The proc command accepts three arguments:

  1. Name of the procedure
  2. List of argument names for the procedure
  3. Tcl script forming the body of the procedure

Example:

proc greetWorld {} {
    puts "Hello World!"
}
greetWorld

Output:

Hello World!

Return Command

To exit a procedure early without completing its entire script, use the return command. It causes the enclosing procedure to return immediately.

Example:

proc factorial n {
    if {$n <= 1} {
        return 1
    }
    expr $n * [factorial [expr $n - 1]]
}
puts [factorial 4]
puts [factorial 0]

Output:

24
1

Example with Multiple Arguments

Example:

proc add {x y} {
    return [expr $x + $y]
}
puts [add 10 30]

Output:

40

Default Arguments

Default arguments provide default values when no value is supplied.

Example:

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

Output:

40
110

Procedures with Variable Arguments

Example:

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

Output:

65
66

Local and Global Variables

In the body of a Tcl procedure, variables assigned or passed are called local variables, accessible only within the procedure. Variables referenced outside any procedure are global variables. To reference global variables within a procedure, use the global command.

Example:

proc accumulate {str} {
    global accumulator
    append accumulator $str "\n"
}

Upvar Command

The upvar command provides a mechanism for accessing variables outside the context of a procedure.

Example (To print the contents of an array):

proc printArray name {
    upvar $name arr
    foreach element [lsort [array names arr]] {
        puts "$element = $arr($element)"
    }
}
set info(age) 37
set info(position) "Vice President"
printArray info

Output:

age = 37
position = "Vice President"

Error Handling in TCL

Errors in Tcl commands can occur for various reasons, such as nonexistent commands, incorrect number of arguments, or malformed arguments.

Example:

set list {44 16 123 98 57}
set total 0
foreach el $list {
    set total [expr $total + $element]
}

The script will be aborted with the error message: can’t read "element": no such variable.

Trapping Errors - Catch Command

The catch command is used to continue executing a script even after an error occurs. It takes two arguments: the script to execute and a variable to hold the error or result.

Example:

set message
catch {unset x} message
puts $message

Output:

can’t unset "x": no such variable

Handling Exceptions

Exceptions in Tcl include errors, as well as the break, continue, and return commands, which cause work in progress to be aborted.

Example:

catch {return "all done"} result
puts $result

Output:

all done

Example: Div Function

Example:

proc Div {a b} {
    if {$b == 0} {
        error "Error generated by error" "Info String for error" 401
    } else {
        return [expr $a / $b]
    }
}
if {[catch {puts "Result = [Div 10 0]"} errmsg]} {
    puts "ErrorMsg: $errmsg"
    puts "ErrorCode: $errorCode"
    puts "ErrorInfo:\n$errorInfo\n"
}
if {[catch {puts "Result = [Div 10 2]"} errmsg]} {
    puts "ErrorMsg: $errmsg"
    puts "ErrorCode: $errorCode"
    puts "ErrorInfo:\n$errorInfo\n"
}

Output:

ErrorMsg: Error generated by error
ErrorCode: 401
ErrorInfo:
Info String for error
(procedure "Div" line 1)
invoked from within
"Div 10 0"
Result = 5
© 2025 semihub.in. All rights reserved.