subroutine
The subroutine
keyword is used to define a named subroutine
Syntax
Details
Overview
A subroutine is a named section of code that can be executed multiple times on demand from anywhere in the script. When called (via the gosub statement), execution of the script jumps to the start of the specified subroutine. When the end of the code in the subroutine body is reached or a return statement is encountered (whichever comes first), execution resumes at the statement following the most recent gosub statement that was executed.
The code in the body of a subroutine
statement is never executed unless the subroutine is explicitly called using gosub. If a subroutine is encountered during normal linear execution of the script then the code in it will be ignored.
Subroutines in USE do not return any values, but any variables that are set within the subroutine can be accessed from anywhere in the script and as such they should be used for returning values as needed.
Subroutine Arguments
When invoked via the gosub statement, arguments can be passed to the subroutine. These arguments are read-only but may be copied to normal variables if required.
Arguments are accessed using the same syntax as is used for variables as follows:
${SUBARG.COUNT}
contains the number of arguments that were passed to the subroutine
${SUBARG_N}
is the value of any given argument, where N
is the number of the argument starting at 1
Every time a subroutine is called, any number of arguments may be passed to it. These arguments are local to the subroutine and will be destroyed when the subroutine returns. However, copying an argument to a standard variable will preserve the original value as follows:
After the subroutine above has been executed the return_value
variable will retain the value it was set to.
It is not permitted to nest subroutine
statements. If used within the body of a subroutine statement, a subroutine
statement will cause the script to terminate with an error.
Example
The following demonstrates using a subroutine to detect when another subroutine has been provided with an incorrect number of arguments:
Last updated