Driver-scoped variables have some limitations. For instance, they are not suitable for recursion, but local-scoped variables are suitable.

The following example shows a script that uses recursion and a driver-scoped variable. At first glance, the script looks like it reverses the order of words that are passed to it. A driver-scoped variable x with a record lifetime is used to store a value each time a rule is executed. Unfortunately, each time the recursion executes, the word assigned to the variable overwrites the existing value. The last value assigned to x is the value that is used for all of the recursions. Only the last word appears as output.

ASL Script (2ndrule_var.asl):
START {
 READANDPRINT
}
READANDPRINT {
 x:word READANDPRINT|eol
}
do {
 print(x);
}
Input (2ndrule_var.txt):
The dog ran.
Output:
$ sm_adapter --file=2ndrule_var.txt 2ndrule_var.asl
ran.
ran.
ran.
ran.
$ 

Local variables are defined in a rule and have a separate value each time the rule runs. Local variables can be referenced in any subordinate rules. They cannot be accessed in any other rule. A local variable cannot have the same name as a global variable.

If a local variable is used in a recursive rule, each recursion contains an exclusive value for the variable, as shown in Figure 5 on page 37.

Local variables are declared in the pattern block of a rule. These declarations must occur before any pattern matching statements. Local variables override variables with the same name. Use this syntax to declare a local variable:

local <variable_name>;

The following example demonstrates how use of a local variable instead of a driver-scoped variable changes the output of the script.

The script reverses the order of words. The rule READANDPRINT iterates until it does not match. For each iteration, the value of the word scanned is stored in a local variable. When the end-of-line (eol) marker is reached, the READANDPRINT rule no longer matches and the recursive rules are completed with the action block. Each value of x is printed, which has the effect of reversing the order of the input. The section “End-of-line matches” on page 58 provides additional more information about eol markers.

ASL Script (local_var.asl):
START {
 READANDPRINT
}
READANDPRINT {
 local x = “end”;
 x:word 
 READANDPRINT|eol
}
do {
 print(x);
}
Input: (local_var.txt):
The dog ran.
Output:
$ sm_adapter --file=local_var.txt local_var.asl
end
ran.
dog
The
$