gawk: Switch Statement

1 
1 7.4.5 The 'switch' Statement
1 ----------------------------
1 
1 This minor node describes a 'gawk'-specific feature.  If 'gawk' is in
1 compatibility mode (⇒Options), it is not available.
1 
1    The 'switch' statement allows the evaluation of an expression and the
1 execution of statements based on a 'case' match.  Case statements are
1 checked for a match in the order they are defined.  If no suitable
1 'case' is found, the 'default' section is executed, if supplied.
1 
1    Each 'case' contains a single constant, be it numeric, string, or
1 regexp.  The 'switch' expression is evaluated, and then each 'case''s
1 constant is compared against the result in turn.  The type of constant
1 determines the comparison: numeric or string do the usual comparisons.
1 A regexp constant does a regular expression match against the string
1 value of the original expression.  The general form of the 'switch'
1 statement looks like this:
1 
1      switch (EXPRESSION) {
1      case VALUE OR REGULAR EXPRESSION:
1          CASE-BODY
1      default:
1          DEFAULT-BODY
1      }
1 
1    Control flow in the 'switch' statement works as it does in C. Once a
1 match to a given case is made, the case statement bodies execute until a
1 'break', 'continue', 'next', 'nextfile', or 'exit' is encountered, or
1 the end of the 'switch' statement itself.  For example:
1 
1      while ((c = getopt(ARGC, ARGV, "aksx")) != -1) {
1          switch (c) {
1          case "a":
1              # report size of all files
1              all_files = TRUE;
1              break
1          case "k":
1              BLOCK_SIZE = 1024       # 1K block size
1              break
1          case "s":
1              # do sums only
1              sum_only = TRUE
1              break
1          case "x":
1              # don't cross filesystems
1              fts_flags = or(fts_flags, FTS_XDEV)
1              break
1          case "?":
1          default:
1              usage()
1              break
1          }
1      }
1 
1    Note that if none of the statements specified here halt execution of
1 a matched 'case' statement, execution falls through to the next 'case'
1 until execution halts.  In this example, the 'case' for '"?"' falls
1 through to the 'default' case, which is to call a function named
1 'usage()'.  (The 'getopt()' function being called here is described in
1 ⇒Getopt Function.)
1