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 5: Expressions 85foo += 5This is equivalent to the following:foo = foo + 5Use whichever makes the meaning of your program clearer.There are situations where using ‘+=’ (or any assignment operator) is not the same assimply repeating the lefthand operand in the righthand expression. For example:# Thanks to Pat Rankin for this exampleBEGIN {foo[rand()] += 5for (x in foo)print x, foo[x]}bar[rand()] = bar[rand()] + 5for (x in bar)print x, bar[x]The indices of bar are practically guaranteed to be different, because rand returns differentvalues each time it is called. (Arrays and the rand function haven’t been covered yet. SeeChapter 7 [Arrays in awk], page 119, and see Section 8.1.2 [Numeric Functions], page 130, formore information). This example illustrates an important fact about assignment operators:the lefthand expression is only evaluated once. It is up to the implementation as to whichexpression is evaluated first, the lefthand or the righthand. Consider this example:i = 1a[i += 2] = i + 1The value of a[3] could be either two or four.Table 5.2 lists the arithmetic assignment operators. In each case, the righthand operandis an expression whose value is converted to a number.Operatorlvalue += incrementlvalue -= decrementlvalue *= coefficientlvalue /= divisorlvalue %= moduluslvalue ^= powerlvalue **= powerEffectAdds increment to the value of lvalue.Subtracts decrement from the value of lvalue.Multiplies the value of lvalue by coefficient.Divides the value of lvalue by divisor.Sets lvalue to its remainder by modulus.Raises lvalue to the power power.Table 5.2: Arithmetic Assignment OperatorsNOTE: Only the ‘^=’ operator is specified by POSIX. For maximum portability,do not use the ‘**=’ operator.

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

Saved successfully!

Ooh no, something went wrong!