2.18. Subroutines

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

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

Variables listed in parentheses after the subroutine name are the parameters to the subrouting and 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. Type declarations optionally precede the parameter variable and will restrict any arguments passed to the type declared. The same subrouting can be declared multiple times if each declaration has different parameter types; this is called overloading the subroutine.

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

The return type of the subroutine can be given by listing a type declaration after the returns keyword after the parentheses after the subroutine name.

Note that parameter and return types are required when the PO_REQUIRE_TYPES or PO_REQUIRE_PROTOTYPES parse options are set.

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 $string) returns int {
    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(int $num) returns int {
    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.