manpagez: man pages & more
info gawk
Home | html | info | man
[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

7.4.5 The switch Statement

The switch statement allows the evaluation of an expression and the execution of statements based on a case match. Case statements are checked for a match in the order they are defined. If no suitable case is found, the default section is executed, if supplied.

Each case contains a single constant, be it numeric, string, or regexp. The switch expression is evaluated, and then each case’s constant is compared against the result in turn. The type of constant determines the comparison: numeric or string do the usual comparisons. A regexp constant does a regular expression match against the string value of the original expression. The general form of the switch statement looks like this:

switch (expression) {
case value or regular expression:

Control flow in the switch statement works as it does in C. Once a match to a given case is made, the case statement bodies execute until a break, continue, next, nextfile or exit is encountered, or the end of the switch statement itself. For example:

switch (NR * 2 + 1) {
case 3:
case "11":
    print NR - 1

case /2[[:digit:]]+/:
    print NR

    print NR + 1

case -1:
    print NR * -1

Note that if none of the statements specified above halt execution of a matched case statement, execution falls through to the next case until execution halts. In the above example, for any case value starting with ‘2’ followed by one or more digits, the print statement is executed and then falls through into the default section, executing its print statement. In turn, the -1 case will also be executed since the default does not halt execution.

This switch statement is a gawk extension. If gawk is in compatibility mode (see section Command-Line Options), it is not available.

[ << ] [ < ] [ Up ] [ > ] [ >> ]         [Top] [Contents] [Index] [ ? ]

This document was generated on March 30, 2012 using texi2html 5.0.

© 2000-2015
Individual documents may contain additional copyright information.