3.3.2.60 Switch

The switch command is a special multi-way decision maker that tests whether an expression matches one of a number of values, and branches accordingly.


Syntax:

switch (expression) {case 1: . . . case 2: . . . case n: . . . [default: . . .]}

The value can be either a constant, an identifier, or a string variable. When expression is a string variable, the evaluation is case-sensitive (see the Examples). Each case requires a break command, so the following commands are not executed. A default case can also be used, and should come last (when nesting switch commands, the default case must come last). The default case is executed only when no other case is matched.

Note: The case, default, and to keywords are case-insensitive.

Examples:

Example 1:

The following script uses the switch command. Because the expression in the parentheses following the switch command is the variable ii which evaluates to 2, case 2 is executed. The result from this script is b.

If the expression evaluates to a string, string substitution is required, e.g. switch (%(Col(A[ii]$)).

ii=2;
switch (ii)
      {
            case 1:
                  type "a"; 
                  break;
            case 2:
                  type "b"; 
                  break;
            case 3:
                  type "c"; 
                  break;
            default:
                  type "none"; 
                  break;
      }

Example 2:

In the following example, the expression in the parentheses following the switch command is a string variable, so its evaluation is case-sensitive. However, the keywords case, default, and to are case-insensitive.

GetString "Enter a string";   // input is put in %B
switch (%B)  
      {
            CASE "a":
                  type -a "You entered an 'a'.";  
                  break;
            case "b": CASE "c":  
                  type -a "You entered a 'b' or 'c'.";
                  break;
            case "A":
                  type -a "You entered an 'A'.";
                  break;
            case "A" "B" "F" to "Z":
                  type -a "You entered 'A' or 'B' or between 'F' and 'Z'.";
                  break;
            case 1 2 5 to 7:
                  type -a "You entered 1 or 2 or between 5 and 7.";
                  break;
            default:
                  type -a "No match, this is the default case.";
                  break;
      }

Note that the lexical order is AaBbCc... so 'b' and 'B' would both be found by: case "A" to "C":

See Also:

Break (command), If (command)


Continue (command), Document (command), Exit (command), For (command), Loop (command), Repeat (command),