Non-block statements in Qore are always terminated by a semi-colon ";" as in Perl, 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):
Table 2.86. Qore Statements
Type | Examples | Reference |
---|---|---|
An expression that changes an lvalue | $var = 1;
$var += 5;
$var[1].count++;
shift $var.key[$i]; | |
An expression with the new operator | new ObjectClass(1, 2, 3); | |
An expression with the background operator | background function(); | |
A call reference or closure call | $call_reference($arg1, $arg2); | |
A method call | $object.method(1, 2, 3); | |
An if statement | if ($var == 3) | if and else statements |
An "if ... else" statement | if ($var == 3) | if and else statements |
A while statement | while ($var < 10)
| while statements |
A do while statement | do | do while statements |
A for statement | for ( | for statements |
A foreach statement | foreach | foreach statements |
A switch statement | switch ( | switch statements |
A return statement | return | return statements |
A local variable declaration |
my $var; my ($a, $b, $c); | |
A global variable declaration |
our $var; our ($a, $b, $c); | |
A function call | calculate($this, $that, $the_other); | |
A continue statement | continue; | continue statements |
A break statement | break; | break statements |
A statement block | { | one or more statements enclosed in curly brackets. |
A delete statement | delete | delete statements |
A throw statement | throw | throw statements |
try and catch statements | try | try and catch statements |
A rethrow statement | rethrow; | rethrow statements |
A thread_exit statement | thread_exit; | thread_exit statements |
A context statement |
context | context statements |
A summarize statement |
summarize | summarize statements |
A subcontext statement | subcontext
| subcontext statements |
An on_exit statement | on_exit
| on_exit statements |
An on_success statement | on_success
| on_success statements |
An on_error statement | on_error
| on_error statements |
The if statement allows for conditional logic in a Qore program's flow; the syntax is similar to that of C, C++, or Java.
if (expression
)statement
[elsestatement
]
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.
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).
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.
for ([initial_expression]
;[test_expression]
;[iterator_expression]
)statement
[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
.
Here is an example of a for loop using a local variable:
for (my $i = 0; $i < 10; $i++) print("%d\n", $i);
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.
foreach [my]$variable
in (expression
)statement
If the 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.
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 my $string in (\$str_list) trim $string;
Note that 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.
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.
switch (expression
) { casecase_expression
:statement(s)
... [ default :statement(s)
] }
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; }
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.
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.
Table 2.87. Valid Case Expression Operators
Operator | Description |
---|---|
> | |
>= | |
< | |
<= | |
== | |
~= | regular expression match operator (in this case the regular expression may be optionally given without the operator) |
!~ |
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.
while (expression
)statement
First the expression
will be evaluated; if it evaluates to True, then statement
will be executed. If it evaluates to False, the loop terminates.
$a = 1;
while ($a < 10)
$a++;
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.
dostatement
while (expression
);
First, statement
will be executed, then 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.
$a = 1; do $a++; while ($a < 10);
Skips the rest of a loop and jumps right to the evaluation of the iteration expression.
continue;
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.
Exits immediately from a loop statement or switch block.
break;
The break statement affects loop processing; that is; it has an affect on for, while, do while, context, summarize, and subcontext loop 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.
In order to delete the contents of an lvalue, the delete statement can be used. For objects, this will also run the destructor method (if defined for the class).
delete $lvalue;
In order to throw an exception explicitly, the throw statement must be used.
throw expression;
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 and 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.
Some error conditions can only be detected and handled using exception handlers. To catch exceptions, try and catch statements can 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.
trystatement
catch ([$exception_hash_variable
])statement
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.
A rethrow statement can be used to rethrow an exception in a catch block. In this case a entry tagged as a rethrow entry will be placed on the exception call stack. 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).
rethrow;
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. Note that it is an error to call rethrow outside of a catch block.
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.
thread_exit;
This statement will cause the current thread to stop executing immediately.
To easily iterate through multiple rows in a hash of arrays (such as a query result set returned by the Datasource::select() method), 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.
context [name] (data_expression )
[ where (expression
) ] [ sortBy (expression
) ] [ sortDescendingBy (expression
) ]statement
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.
[ sortBy (
expression
) ]
An optional sort_by 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).
[ sortDescendingBy (
expression
) ]
Another optional modifier to the context statement that behaves the same as above except that the results are sorted in descending order.
# 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) { printf("%s: start date: %s\n", %msisdn, format_date(%effective_start_date, "YYYY-MM-DD HH:mm:SS")); }
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.
summarize (expression
) by (expression
) [ where (expression
) ] [ sortBy (expression
) ] [ sortDescendingBy (expression
) ]statement
summarize statements modifiers have the same effect as those for the context statement, except for the following:
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.
# 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(%effective_start_date, "YYYY-MM-DD HH:mm:SS")); }
Statement used to loop through values within a summarize statement.
subcontext [ where (expression
) ] [ sortBy (expression
) ] [ sortDescendingBy (expression
) ]statement
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.
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(%effective_start_date, "YYYY-MM-DD HH:mm:SS")); subcontext sortDescendingBy (%effective_end_date) { printf("\tservice %s: ends: %s\n", %msisdn, format_date(%effective_end_date, "YYYY-MM-DD HH:mm:SS")); } }
return statements causes the flow of execution of the subroutine, 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.
return [expression
];
This statement causes execution of the current subroutine, method, or program to cease and optionalls returns a value to the caller.
sub getName() { return "Barney"; } $name = getName();
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.
on_exit
statement
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 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. Even if an exception is raised or a return statement is executed, any on_exit code that is queued will be executed. 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).
{ $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
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.
on_success
statement
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 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 conditional execution when the block is exited. Even if a return statement is executed later in the block, any on_exit code that is queued will be executed as long as there is no active (unhandled) exception. 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).
{ $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
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_success statement and related to the on_exit statement.
on_error
statement
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 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 conditional execution when the block is exited. Even if a return statement is executed later in the block, any on_exit code that is queued will be executed as long as there is an active (unhandled) exception. 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.
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.
{ $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