wiki:Doc/panc/dml/flow

Flow Control

DML contains three statements that permit non-linear execution of code within a DML block. The 'if' statement allows conditional branches, the 'while' statement allows looping over a DML block, and the 'foreach' statement allows iteration over an entire resource (list or hash).

These statements, like all DML statements, return a value. Be careful of this, because unexecuted blocks generally will return 'undef', which may lead to non-intuitive behavior.

Branching (If Statement)

The 'if' statement allows conditional execution of a DML block. The statement may include an 'else' clause that will be executed if the condition is false. The syntax is:

if ( condition-dml ) true-dml;
if ( condition-dml ) true-dml else false-dml;

where all of the blocks may either be a single DML statement or a true DML block.

The value returned by this statement is the value returned by the true-dml or false-dml block, whichever is actually executed. If the 'else' clause is not present and the condition-dml is false, the if statement returns 'undef'.

Looping (While Statement)

Looping behavior is provided by the 'while' statement. The syntax is:

while ( condition-dml ) body-dml;

The loop will continue until the condition-dml evaluates as false. The value of this statement is that returned by the body-dml block. If the body-dml block is never executed, then 'undef' is returned.

Note that the compiler usually enforces an iteration limit to avoid infinite loops. Loops exceeding the iteration limit will cause the compiler to abort the execution.

Iteration (Foreach Statement)

The 'foreach' statement allows iteration over all of the elements of a list or hash. The syntax is:

foreach (key; value; resource) body-dml;

This will cause the body-dml to be executed once for each element in resource (a list or hash). The local variables 'key' and 'value' (you can choose these names) will be set at each iteration to the key and value of the element. For a list, the key is the element's index. The iteration will always occur in the natural order of the resource: ordinal order for lists and lexical order of the keys for hashes.

The value returned will be that of the last iteration of the body-dml. If the body-dml is never executed (for an empty list or hash), 'undef' will be returned.

The 'foreach' statement is not subject to the compiler's iteration limit. By definition, the resource has a finite number of entries, so this safeguard is not needed.

This form of iteration should be used in preference to the first/next functions or the key function whenever possible. It is more efficient than the functional forms and less prone to error.

Last modified 17 years ago Last modified on Jun 15, 2007, 8:41:09 PM