21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 6: Patterns, Actions, and Variables 105The same is true of the increment part. Incrementing additional variables requiresseparate statements at the end of the loop. The C compound expression, using C’s commaoperator, is useful in this context but it is not supported in awk.Most often, increment is an increment expression, as in the previous example. But thisis not required; it can be any expression whatsoever. For example, the following statementprints all the powers of two between 1 and 100:for (i = 1; i 0;)’ is equivalent to ‘while (x > 0)’.If the condition is omitted, it is treated as true, effectively yielding an infinite loop (i.e., aloop that never terminates).In most cases, a for loop is an abbreviation for a while loop, as shown here:initializationwhile (condition) {bodyincrement}The only exception is when the continue statement (see Section 6.4.7 [The continueStatement], page 107) is used inside the loop. Changing a for statement to a whilestatement in this way can change the effect of the continue statement inside the loop.The awk language has a for statement in addition to a while statement because a forloop is often both less work to type and more natural to think of. Counting the numberof iterations is very common in loops. It can be easier to think of this counting as part oflooping rather than as something to do inside the loop.6.4.5 The switch StatementNOTE: This subsection describes an experimental feature added in gawk 3.1.3.It is not enabled by default. To enable it, use the ‘--enable-switch’ optionto configure when gawk is being configured and built. See Section B.2.2 [AdditionalConfiguration Options], page 269, for more information.The switch statement allows the evaluation of an expression and the execution of statementsbased on a case match. Case statements are checked for a match in the order theyare 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 switchexpression is evaluated, and then each case’s constant is compared against the result inturn. The type of constant determines the comparison: numeric or string do the usualcomparisons. A regexp constant does a regular expression match against the string valueof the original expression. The general form of the switch statement looks like this:switch (expression) {case value or regular expression:case-bodydefault:default-body

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!