Cobra Inline Programs keywords

NAME

control-flow keywords

DESCRIPTION

The following ten words are keywords used for definint the control-flow of an inline program. We illustrate the typical use of each keyword with a small example.

Note that the body of every if, else, while, and for statement must be enclosed in curly braces, even if it contains just a single statement. Also, every basic statement (not compound statements) must be terminated with a semi-colon.

if and else if ( expr ) { prog }
if ( expr ) { prog1 } else { prog2 }
while, break, and continue while ( expr ) { prog }
where prog can contain break and/or continue statements
goto goto label; prog1
label: prog2
for for (i in A) { prog } see assiociative arrays
function and return see user-defined functions

The destination of a goto can either follow or precede the location of the goto itself, but it must appear within the same program fragment, or within the same function definition as the goto.

For statements are only used for browsing the contents of associative arrays. The only general loop statement is the while-loop, where the break and continue statements have the usual effect, which is respectively to break from the innermost loop, or to shortcut the current iteration and jump back to the loop condition to start a new iteration. For instance, we can make an inline program take over the complete traversal of all tokens in the input sequence as follows:

	%{
		. = Begin;
		while (. != End)
		{	# do something useful
			. = .nxt;	# dont forget this
		}
		Stop;
	%}
Technically, both the first and last statement here are redundant, because when the inline program is invoked for the first time the current token will be the first token in the input sequence, and in this case when the while loop terminates we also know that we have reached the final token, so the Cobra will not advance the token any further and stop executing, even if the Stop command was not there. Typically though it is not wise to count on these two things being true.

We could use the above loop to reverse the order of traversal, if that made sense in some context, and then we definitely need the two extra statements:

	%{
		. = End;
		while (. != Begin)
		{	# do something
			. = .prv;
		}
		Stop;
	%}
This time, if we were to forget the Stop command, the program execution would never finish: it would continued to execute because after each execution the current token position is back at the beginning of the input sequence.

Inline Programs
Manual
Tutorial
(Last Updated: 11 May 2019)