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.

192 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>}If the assertion fails, you see a message similar to the following:mydata:1357: assertion failed: a = 17.1There is a small problem with this version of assert. An END rule is automaticallyadded to the program calling assert. Normally, if a program consists of just a BEGIN rule,the input files and/or standard input are not read. However, now that the program has anEND rule, awk attempts to read the input data files or standard input (see Section 6.1.4.1[Startup and Cleanup Actions], page 99), most likely causing the program to hang as itwaits for input.There is a simple workaround to this: make sure the BEGIN rule always ends with anexit statement.12.2.4 Rounding NumbersThe way printf and sprintf (see Section 4.5 [Using printf Statements for Fancier Printing],page 61) perform rounding often depends upon the system’s C sprintf subroutine.On many machines, sprintf rounding is “unbiased,” which means it doesn’t always rounda trailing ‘.5’ up, contrary to naive expectations. In unbiased rounding, ‘.5’ rounds toeven, rather than always up, so 1.5 rounds to 2 but 4.5 rounds to 4. This means that if youare using a format that does rounding (e.g., "%.0f"), you should check what your systemdoes. The following function does traditional rounding; it might be useful if your awk’sprintf does unbiased rounding:# round.awk --- do normal roundingfunction round(x, ival, aval, fraction){ival = int(x) # integer part, int() truncates# see if fractional partif (ival == x) # no fractionreturn ival # ensure no decimals}if (x < 0) {aval = -x # absolute valueival = int(aval)fraction = aval - ivalif (fraction >= .5)return int(x) - 1 # -2.5 --> -3elsereturn int(x) # -2.3 --> -2} else {fraction = x - ivalif (fraction >= .5)return ival + 1elsereturn ival}

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

Saved successfully!

Ooh no, something went wrong!