switch statement

The switch statement is a multi-way decision making mechanism which tests whether an expression matches one of a number of given values, and carry out corresponding commands accordingly. The following is the general form of a switch statement.
	   switch expression
          case value1
               statement group 1
          case value2
               statement group 2
          ...
          default
               statement group
      end
It is equivalent to the following if statement
         if expression == value1
               statement group 1
         elseif expression == value2
               statement group 2
          ...
         else
               statement group
      end
The default clause in the switch statement is optional.

Besides the case keyword, one can also use cases. For example,

      switch word
          case value
               statement group 1
          cases values
               statement group 2
       end
Here, if word is equal to value, statement group 1 will be executed. If word is not equal to value, but it is a member of the set values, then statement group 2 will be executed. It is equivalent to the following if statement
         if expression == value
               statement group 1
         elseif expression in values
               statement group 2
         end
The following code reads lines of text and count the words in them that start with a, b, c, and d.
   T @ "a" = 0;  // set counters to zero
   T @ "b" = 0;
   T @ "c" = 0;
   T @ "d" = 0;
   T @ "?" = 0;
   while 1
     line = readline();  // read a line
     words = split(line, " "); // split the line to a list of words
     for k = 1 : (# words)     // loop over all words
       switch words # k
         cases ~/^ *[aA]/;   // word starts with a or A
             T @ "a" = T @ "a" + 1;
         cases ~/^ *[bB]/;  // word starts with b or B
             T @ "b" = T @ "b" + 1;
         cases ~/^ *[cC]/;
             T @ "c" = T @ "c" + 1;
         cases ~/^ *[dD]/;
             T @ "d" = T @ "d" + 1;
         default
             T @ "?" += 1; 
       end
     end 
   end



oz 2009-12-22