21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

94 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>A function can also have side effects, such as assigning values to certain variables or doingI/O. This program shows how the ‘match’ function (see Section 8.1.3 [String-ManipulationFunctions], page 132) changes the variables RSTART and RLENGTH:{if (match($1, $2))print RSTART, RLENGTHelseprint "no match"}Here is a sample run:$ awk -f matchit.awkaaccdd c+⊣ 3 2foo bar⊣ no matchabcdefg e⊣ 5 15.14 Operator Precedence (How Operators Nest)Operator precedence determines how operators are grouped when different operators appearclose by in one expression. For example, ‘*’ has higher precedence than ‘+’; thus, ‘a + b *c’ means to multiply b and c, and then add a to the product (i.e., ‘a + (b * c)’).The normal precedence of the operators can be overruled by using parentheses. Think ofthe precedence rules as saying where the parentheses are assumed to be. In fact, it is wiseto always use parentheses whenever there is an unusual combination of operators, becauseother people who read the program may not remember what the precedence is in this case.Even experienced programmers occasionally forget the exact rules, which leads to mistakes.Explicit parentheses help prevent any such mistakes.When operators of equal precedence are used together, the leftmost operator groupsfirst, except for the assignment, conditional, and exponentiation operators, which group inthe opposite order. Thus, ‘a - b + c’ groups as ‘(a - b) + c’ and ‘a = b = c’ groups as ‘a =(b = c)’.Normally the precedence of prefix unary operators does not matter, because there is onlyone way to interpret them: innermost first. Thus, ‘$++i’ means ‘$(++i)’ and ‘++$x’ means‘++($x)’. However, when another operator follows the operand, then the precedence of theunary operators can matter. ‘$x^2’ means ‘($x)^2’, but ‘-x^2’ means ‘-(x^2)’, because ‘-’has lower precedence than ‘^’, whereas ‘$’ has higher precedence. Also, operators cannot becombined in a way that violates the precedence rules; for example, ‘$$0++--’ is not a validexpression because the first ‘$’ has higher precedence than the ‘++’; to avoid the problemthe expression can be rewritten as ‘$($0++)--’.This table presents awk’s operators, in order of highest to lowest precedence:(...) Grouping.$ Field.++ -- Increment, decrement.

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

Saved successfully!

Ooh no, something went wrong!