2.16. Subroutines

A subroutine is declared in Qore by using the key word sub as follows:

sub subroutine_name([variable1, variable2, ...]) {
    statements;
}

Variables listed in parentheses by the subroutine name automatically get local lexical scoping. In order to process a variable number of arguments to a function, the $argv variable (local variable) is instantiated as a list with the remaining arguments passed to the subroutine.

Subroutines can use the return statement to provide a return value. Subroutine names must be valid Qore identifiers.

Note

Variables passed as function arguments are passed by value by default, unless the caller places a "\" character before an lvalue in the argument list. In this case the subroutine must have a parameter defined to accept the variable passed by reference. Any changes to the local variable will be reflected in the original variable for variables passed by reference. Also note that it is illegal to pass an argument by reference in a background expression.

Subroutines can return values to the calling expression by using the return statement, with the following syntax:

return expression;

Here is an example subroutine declaration for a function returning a value:

#!/usr/bin/qore
#
# subroutine declaration example

sub print_string($string) {
    print("%s\n", $string);
    return 1;
}

Subroutines may also be recursive. Here is an example of a recursive Qore subroutine definition implementing the Fibonacci function:

#!/usr/bin/qore
#
# recursive subroutine example

sub fibonacci($num) {
    if ($num == 1)
        return 1;
    return $num * fibonacci($num - 1);
}

Note

Function names are resolved during the second parse pass; therefore functions do not need to be declared before being referenced. This allows an easy definition of 2 or more self-referencing functions.