Qore Programming Language Reference Manual 2.0.0
Loading...
Searching...
No Matches
Statements

Non-block statements in Qore are always terminated by a semi-colon ";" as in Perl, C, C++, or Java. Statements can be grouped into blocks, which are delimited by curly brackets "{" and "}" containing zero or more semi-colon delimited statements, as in C or Java. Like C, C++, and Java, but unlike perl, any Qore statement taking a statement modifier will accept a single statement or a statement block.

A statement can be any of the following (note that statements are also recursively defined, and note furthermore that all examples are given in %new-style):

Qore Statements

Type Examples Reference
An expression that changes an lvalue
var = 1;
var += 5;
var[1].count++;
shift var.key[i];
Expressions
An expression with the new operator
new ObjectClass(1, 2, 3);
New Value Operator (new)
An expression with the background operator
background function();
Background Operator (background)
An if statement
if (var == 3) {}
if and else Statements
An if ... else statement
if (var == 3) {} else {}
if and else Statements
A while statement
while (var < 10) {}
while Statements
A do while statement
do {} while (True);
do while Statements
A for statement
for (int i = 0; i < 10; ++ i) {}
for Statements
A foreach statement
foreach softint i in (list) {}
foreach Statements
A switch statement
switch (var) { case =~ /error/: throw "ERROR", var; default: printf("%s\n", var); }
switch Statements
A return statement
return val;
return Statements
A local variable declaration
string var;
my (int a, string b, bool c);
Variables, Variable Declarations and Lexical Scope
A global variable declaration
our int var;
our (float a, int b, hash c);
Variables, Variable Declarations and Lexical Scope
A function call
calculate(this, that, the_other);
Functions, Object Method Calls, Static Method Calls, Closures, Call References
A continue statement
continue;
continue Statements
A break statement
break;
break Statements
A statement block
{}
zero or more statements enclosed in curly brackets
A throw statement
throw "ERROR", description;
throw Statements
A try and catch statement
try { func(); } catch (hash ex) { printf("%s:%d: %s: %s\n", ex.file, ex.line, ex.err, ex.desc); }
try and catch Statements
A rethrow statement
rethrow;
rethrow Statements
A thread_exit statement
thread_exit;
thread_exit Statements
A context statement
context top (q) {}
context Statements
A summarize statement
summarize (q) by (%date) where (%id != NULL) {}
summarize Statements
A subcontext statement
subcontext where (%type == "INBOUND" ) {}
subcontext Statements
An on_exit statement
on_exit l.unlock();
on_exit Statements
An on_success statement
on_success ds.commit();
on_success Statements
An on_error statement
on_error ds.rollback();
on_error Statements

if and else Statements

Synopsis
The if statement allows for conditional logic in a Qore program's flow; the syntax is similar to that of C, C++, or Java.
Syntax
if (expression)
    statement
[else
    statement]
Description
Qore if statements work like if statements in C or Java. If the result of evaluating the expression converted to a Boolean value is True, then the first statement (which can also be a block) is executed. If the result is False, and there is an else keyword after the first statement, the following statement is executed.
Note
Any expression that evaluates to a non-zero integer value will be converted to a Boolean True. Any expression that evaluates to zero value is interpreted as False. This is more like C and Java's behavior and not like Perl's (where any non-null string except "0" is True). To simulate Perl's boolean evaluation, use <value>::val().

for Statements

Synopsis
The Qore for statement is most similar to the for statement in C and Java, or the non array iterator for statement in Perl. This statement is ideal for loops that should execute a given number of times, then complete. Each of the three expressions in the for statement is optional and may be omitted. To iterate through a list without directly referencing list index values, see the foreach statement.
Syntax
for ( [initial_expression]; [test_expression]; [iterator_expression])
    statement
Description
[initial_expression]
The initial_expression is executed only once at the start of each for loop. It is typically used to initialize a loop variable.

[test_expression]
The test_expression is executed at the start of each for loop iteration. If this expression evaluates to Boolean False, the loop will terminate.

[iterator_expression]
The iterator_expression is executed at the end of each for loop iteration. It is typically used to increment or decrement a loop variable that will be used in the test_expression.
Example
Here is an example of a for loop using a local variable:
for (int i = 0; i < 10; i++)
print("%d\n", i);

foreach Statements

Synopsis
The Qore foreach statement is most similar to the for or foreach array iterator statement in Perl. To iterate an action until a condition is True, use the for statement instead.
Syntax
foreach [my|our] [type] variable in (expression)
    statement
Description
If expression does not evaluate to a list, then the variable will be assigned the value of the expression evaluation and the statement will only execute one time. Otherwise the variable will be assigned to each value of the list and the statement will be called once for each value.

If expression evaluates to an object inheriting the AbstractIterator class, the foreach operator iterates the object by calling AbstractIterator::next(), and the values assigned to the iterator variable on each iteration are the container values returned by AbstractIterator::getValue().

If possible, expression is evaluated using lazy functional evaluation.

If expression evaluates to NOTHING (no value); then the loop is not executed at all.
Example
Here is an example of a foreach loop using a local variable:
# if str_list is a list of strings, this will remove all whitespace from the
# strings; the reference in the list expression ensures that changes
# to the iterator variable are written back to the list
foreach string str in (\str_list)
trim str;
Here is an example of a foreach loop using an object derived from AbstractIterator:
hash h = ("a": 1, "b": 2);
foreach hash ih in (h.pairIterator())
printf("%s = %y\n", ih.key, ih.value);
Note
  • If a reference (\lvalue_expression) is used as the list expression, any changes made to the foreach iterator variable will be written back to the list (in which case any AbstractIterator object is not iterated; references cannot be used with AbstractIterator objects as such objects provide read-only iteration).
  • When used with %new-style (which is a recommended parse option) or %allow-bare-refs, the my or our keywords are required with new variables or their type has to be declared, otherwise a parse exception will be raised
See also
Map Operator (map) for a flexible way to iterate a list or AbstractIterator object in a single expression

switch Statements

Synopsis
The Qore switch statement is similar to the switch statement in C and C++, except that the case values can be any expression that does not need run-time evaluation and can also be expressions with simple relational operators or regular expressions using the switch value as an implied operand.
Syntax
switch (expression) {
  case case_expression:
    [statement(s)...]
  [default:
    [statement(s)...]]
}
Example
switch (val) {
case < -1:
printf("less than -1\n");
break;
case "string":
printf("string\n");
break;
case > 2007-01-22T15:00:00:
printf("greater than 2007-01-22 15:00:00\n");
break;
case /abc/:
printf("string with 'abc' somewhere inside\n");
break;
default:
printf("default\n");
break;
}
Description
The first expression is evaluated and then compared to the value of each case_expression in declaration order until one of the case_expressions matches or is evaluated to True. In this case all code up to a break statement is executed, at which time execution flow exits the switch statement.

Unless relational operators are used, the comparisons are "hard" comparisons; no type conversions are done, so in order for a match to be made, both the value and types of the expressions must match exactly. When relational operators are used, the operators are executed exactly as they are in the rest of Qore, so type conversions may be performed if nesessary. The only exception to this is when both arguments are strings then a soft comparison is made in order to avoid the case that strings fail to match only because their encodings are different.

To use soft comparisons, you must explicitly specify the soft equals operator as follows:
switch (1) {
case == "1": print("true\n"); break;
}

If no match is found and a default label has been given, then any statements after the default label will be executed. If a match is made, then the statements following that case label are executed.

To break out of the switch statement, use the break statement.

As with C and C++, if no break or return statement is encountered, program control will continue to execute through other case blocks until on of the previous statements is encountered or until the end of the switch statement.

Valid Case Expression Operators

Operator Description
> Greater Than Operator (>)
>= Greater Than Or Equals Operator (>=)
< Less Than Operator (<)
<= Less Than Or Equals Operator (<=)
== Equals Operator (==) (with type conversions)
=~ Regular Expression Match Operator (=~) (in this case the regular expression may be optionally given without the operator)
!~ Regular Expression No Match Operator (!~)

while Statements

Synopsis
while statements in Qore are similar to while statements in Perl, C and Java. They are used to loop while a given condition is True.
Syntax
while (expression)
    statement
Description
First the expression will be evaluated; if it evaluates to True, then statement will be executed. If it evaluates to False, the loop terminates.
Example
int a = 1;
while (a < 10)
a++;

do while Statements

Synopsis
do while statements in Qore are similar to do while statements in C. They are used to guarantee at least one iteration and loop until a given expression evaluates to False.
Syntax
do
    statement
while (expression);
Description
First, the statement will be executed, then the expression will be evaluated; if it evaluates to True, then the loop iterates again. If it evaluates to False, the loop terminates.

The difference between do while statements and while statements is that the do while statement evaluates its loop expression at the end of the loop, and therefore guarantees at least one iteration of the loop.
Example
a = 1;
do
a++;
while (a < 10);

continue Statements

Synopsis
Skips the rest of a loop and jumps right to the evaluation of the iteration expression.
Syntax
continue;
Description
The continue statement affects loop processing; that is; it has an affect on for, foreach, while, do while, context, summarize, and subcontext loop processing.

When this statement is encountered while executing a loop, execution control jumps immediately to the evaluation of the iteration expression, skipping any other statements that might otherwise be executed.

break Statements

Synopsis
Exits immediately from a loop statement or switch block.
Syntax
break;
Description
The break statement affects loop processing; that is; it has an affect on for, foreach, while, do while, context, summarize, and subcontext loop processing as well as on switch block processing.

When this statement is encountered while executing a loop, the loop is immediately exited, and execution control passes to the next statement outside the loop.

throw Statements

Synopsis
In order to throw an exception explicitly, the throw statement must be used.
Syntax
throw expression;
Description
The expression will be passed to the catch block of a try/catch statement, if the throw is executed in a try block. Otherwise the default system exception handler will be run and the currently running thread will terminate.

Qore convention dictates that a direct list is thrown with at least two string elements, the error code and a description. All system exceptions have this format.

See try/catch statements for information on how to handle exceptions, and see Exception Handling for information about how throw arguments are mapped to the exception hash.

try and catch Statements

Synopsis
Some error conditions can only be detected and handled using exception handlers. To catch exceptions, try and catch statements have to be used. When an exception occurs while executing the try block, execution control will immediately be passed to the catch block, which can capture information about the exception.
Syntax
try
    statement
catch ([hash[<ExceptionInfo>]] [exception_hash_variable])
    statement
Description
A single variable can be specified in the catch block to be instantiated with the exception hash, giving information about the exception that has occurred. For detailed information about the exception hash, see Exception Handling .

If no variable is given in the catch declaration, it will not be possible to access any information about the exception in the catch block. However, the rethrow statement can be used to rethrow exceptions at any time in a catch block.

rethrow Statements

Synopsis
A rethrow statement can be used to rethrow an exception in catch and on_error blocks. In this case a entry tagged as a rethrow entry will be placed on the exception call stack.
Syntax
rethrow; rethrow expression;
Description
The rethrown exception will be either passed to the next higher-level catch block, or to the system default exception handler, as with a throw statement.

This statement can be used to maintain coherent call stacks even when exceptions are handled by more than one catch block (for detailed information about the exception hash and the format of call stacks, see Exception Handling).

The second variant taking an expression can be used to enrich or override the original exception; the expression is processed as with throw, except in this case the call stack of the original exception is maintained. Also any exception values not overridden by the rethrow statement remain unchanged. Note that it is an error to use the rethrow statement outside of a catch block.

thread_exit Statements

Synopsis
thread_exit statements cause the current thread to exit immediately. Use this statement instead of the exit() function when only the current thread should exit.
Syntax
thread_exit;
Description
This statement will cause the current thread to stop executing immediately.

context Statements

Synopsis
To easily iterate through multiple rows in a hash of arrays (such as a query result set returned by the Qore::SQL::Datasource::select() or Qore::SQL::SQLStatement::fetchColumns() methods), the context statement can be used. Column names can be referred to directly in expressions in the scope of the context statement by preceding the name with a "%" character, while the current row can be referenced with %%.
Syntax
context [name] (data_expression)
    [where (where_expression)]
    [sortBy (sort_expression)]
    [sortDescendingBy (sort_descending_expression)]
    statement
Description
data_expression
This must evaluate to a hash of arrays in order for the context statement to execute.

where_expression
An optional where expression may be given, in which case for each row in the hash, the expression will be executed, and if the where expression evaluates to True, the row will be iterated in the context loop. If this expression evaluates to False, then the row will not be iterated. This option is given so the programmer can create multiple views of a single data structure (such as a query result set) in memory rather than build different data structures by hand (or retrieve the data multiple times from a database).

sort_expression
An optional sortBy expression may also be given. In this case, the expression will be evaluated for each row of the query given, and then the result set will be sorted in ascending order by the results of the expressions according to the resulting type of the evaluated expression (i.e. if the result of the evaluation of the expression gives a string, then string order is used to sort, if the result of the evaluation is an integer, then integer order is used, etc).

sort_descending_expression
Another optional modifier to the context statement that behaves the same as above except that the results are sorted in descending order.
Example
# note that "%service_type" and "%effective_start_date" represent values
# in the service_history hash of arrays.
context (service_history) where (%service_type == "voice")
sortBy (%effective_start_date) {
# %% is a hash of the current row
check_row(%%);
printf("%s: start date: %s\n", %msisdn, format_date("YYYY-MM-DD HH:mm:SS", %effective_start_date));
}
See also

summarize Statements

Synopsis
summarize statements are like context statements with one important difference: results sets are grouped by a by expression, and the statement is executed only once per discrete by expression result. This statement is designed to be used with the subcontext statement.
Syntax
summarize (data_expression) by (by_expression)
    [where (where_expression)]
    [sortBy (sort_expression)]
    [sortDescendingBy (sort_descending_expression)]
    statement
Description
summarize statements modifiers have the same effect as those for the context statement, except for the following:

by (by_expression)
The by expression is executed for each row in the data structure indicated. The set of unique results defines groups of result rows. For each group of result rows, each row having an identical result of the evaluation of the by expression, the statement is executed only once.
Example
# note that "%service_type" and "%effective_start_date" represent values
# in the services hash of arrays.
summarize (services)
by (%effective_start_date)
where (%service_type == "voice")
sortBy (%effective_start_date) {
printf("account has %d service(s) starting on %s\n",
context_rows(),
format_date("YYYY-MM-DD HH:mm:SS", %effective_start_date));
}
See also

subcontext Statements

Synopsis
Statement used to loop through values within a summarize statement.
Syntax
subcontext
    [where (where_expression)]
    [sortBy (sort_expression)]
    [sortDescendingBy (sort_descending_expression)]
    statement
Description
The subcontext statement is used in conjunction with summarize statements. When result rows of a query should be grouped, and then each row in the result set should be individually processed, the Qore programmer should first use a summarize statement, and then a subcontext statement. The summarize statement will group rows, and then the nested subcontext statement will iterate through each row in the current summary group.
Example
summarize (services)
by (%effective_start_date)
where (%service_type == "voice")
sortBy (%effective_start_date) {
printf("account has %d service(s) starting on %s\n",
context_rows(),
format_date("YYYY-MM-DD HH:mm:SS", %effective_start_date));
subcontext sortDescendingBy (%effective_end_date) {
printf("\tservice %s: ends: %s\n", %msisdn, format_date("YYYY-MM-DD HH:mm:SS", %effective_end_date));
}
}
See also

return Statements

Synopsis
return statements causes the flow of execution of the function, method or program to stop immediately and return to the caller. This statement can take an optional expression to return a value to the caller as well.
Syntax
return [expression];
Description
This statement causes execution of the current function, method, or program to returns to the caller, optionally with a return value.
Example
string sub getName() {
return "Barney";
}
string name = getName();

on_exit Statements

Synopsis
Queues a statement or statement block for unconditional execution when the block is exited, even in the case of exceptions or return statements. For similar statement that queue code for execution depending on the exception status when the block exits, see on_success statements and on_error statements.
Syntax
on_exit
    statement
Description
The on_exit statement provides a clean way to do exception-safe cleanup within Qore code. Any single statment (or statement block) after the on_exit keyword will be executed when the current block exits (as long as the statement itself is reached when executing - on_exit statements that are never reached when executing will have no effect).

The position of the on_exit statement in the block is important, as the immediate effect of this statement is to queue its code for execution when the block is exited, meaning that on_exit statements (along with on_success and on_error statements) are executed in reverse order respective their declaration when the local scope is exited for any reason, even due to an exception or a return statement. Therefore it's ideal for putting cleanup code right next to the code that requires the cleanup.

Note that if this statement is reached when executing in a loop, the on_exit code will be executed for each iteration of the loop.

By using this statement, programmers ensure that necessary cleanup will be performed regardless of the exit status of the block (exception, return, etc).
Example
{
mutex.lock();
# here we queue the unlock of the mutex when the block exits, even if an exception is thrown below
on_exit mutex.unlock();
if (error)
throw "ERROR", "Scary error happened";
print("everything's OK!\n");
return "OK";
}
# when the block exits for any reason, the mutex will be unlocked

on_success Statements

Synopsis
Queues a statement or statement block for execution when the block is exited in the case that no exception is active. Used often in conjunction with the on_error statement and related to the on_exit statement.
Syntax
on_success
    statement
Description
The on_success statement provides a clean way to do block-level cleanup within Qore code in the case that no exception is thrown in the block. Any single statment (or statement block) after the on_success keyword will be executed when the current block exits as long as no unhandled exception has been thrown (and as long as the statement itself is reached when executing - on_success statements that are never reached when executing will have no effect).

The position of the on_success statement in the block is important, as the immediate effect of this statement is to queue its code for execution when the block is exited, meaning that on_success statements (along with on_exit and on_error statements) are executed in reverse order respective their declaration when the local scope is exited for any reason, even due to an exception or a return statement. Therefore it's ideal for putting cleanup code right next to the code that requires the cleanup, along with on_error statements, which are executed in a manner similar to on_success statements, except on_error statements are only executed when there is an active exception when the block is exited.

Note that if this statement is reached when executing in a loop, the on_success code will be executed for each iteration of the loop (as long as there is no active exception).
Example
{
db.beginTransaction();
# here we queue the commit in the case there are no errors
on_success db.commit();
# here we queue a rollback in the case of an exception
on_error db.rollback();
db.select("select * from table where id = %v for update", id);
# .. more code
return "OK";
}
# when the block exits. the transaction will be either committed or rolled back,
# depending on if an exception was raised or not

on_error Statements

Synopsis
Queues a statement or statement block for execution when the block is exited in the case that an exception is active. Used often in conjunction with the on_success statement and related to the on_exit statement.
Syntax
on_error
    statement
Description
The on_error statement provides a clean way to do block-level cleanup within Qore code in the case that an exception is thrown in the block. Any single statment (or statement block) after the on_error keyword will be executed when the current block exits as long as an unhandled exception has been thrown (and as long as the statement itself is reached when executing - on_error statements that are never reached when executing will have no effect).

The position of the on_error statement in the block is important, as the immediate effect of this statement is to queue its code for execution when the block is exited, meaning that on_error statements (along with on_exit and on_error statements) are executed in reverse order respective their declaration when the local scope is exited for any reason, even due to an exception or a return statement. Therefore it's ideal for putting cleanup code right next to the code that requires the cleanup, along with on_success statements, which are executed in a manner similar to on_error statements, except on_success statements are only executed when there is no active exception when the block is exited.

The implicit argument $1 is set to the current active exception, and also rethrow statements are allowed in on_error statements, allowing for exception enrichment. Note that the code in this statement can only be executed once in any block, as a block (even a block within a loop) can only exit the loop once with an active exception (in contrast to on_success and on_exit statements, which are executed for every iteration of a loop).
Example
{
db.beginTransaction();
# here we queue the commit in the case there are no errors
on_success db.commit();
# here we queue a rollback in the case of an exception
on_error {
db.rollback();
# this replaces the exception error code, updated the exception description, and leaves any exception
# argument unchanged
rethrow "TRANSACTION-ERROR", sprintf("%s: $s", $1.err, $1.desc);
}
db.select("select * from table where id = %v for update", id);
# .. more code
return "OK";
}
# when the block exits. the transaction will be either committed or rolled back,
# depending on if an exception was raised or not