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.

190 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>if ((k = index("0123456789", c)) > 0)k-- # adjust for 1-basing in awkelse if ((k = index("abcdef", c)) > 0)k += 9ret = ret * 16 + k}} else if (str ~ /^[-+]?([0-9]+([.][0-9]*([Ee][0-9]+)?)?|([.][0-9]+([Ee][-+]?[0-9]+# decimal number, possibly floating pointret = str + 0} elseret = "NOT-A-NUMBER"}return ret# BEGIN { # gawk test harness# a[1] = "25"# a[2] = ".31"# a[3] = "0123"# a[4] = "0xdeadBEEF"# a[5] = "123.45"# a[6] = "1.e3"# a[7] = "1.32"# a[7] = "1.32E2"## for (i = 1; i in a; i++)# print a[i], strtonum(a[i]), mystrtonum(a[i])# }The function first looks for C-style octal numbers (base 8). If the input string matches aregular expression describing octal numbers, then mystrtonum loops through each characterin the string. It sets k to the index in "01234567" of the current octal digit. Since thereturn value is one-based, the ‘k--’ adjusts k so it can be used in computing the returnvalue.Similar logic applies to the code that checks for and converts a hexadecimal value, whichstarts with ‘0x’ or ‘0X’. The use of tolower simplifies the computation for finding thecorrect numeric value for each hexadecimal digit.Finally, if the string matches the (rather complicated) regex for a regular decimal integeror floating-point number, the computation ‘ret = str + 0’ lets awk convert the value to anumber.A commented-out test program is included, so that the function can be tested with gawkand the results compared to the built-in strtonum function.12.2.3 AssertionsWhen writing large programs, it is often useful to know that a condition or set of conditionsis true. Before proceeding with a particular computation, you make a statement about what

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

Saved successfully!

Ooh no, something went wrong!