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.

76 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>11 Decimal value 11.011 Octal 11, decimal value 9.0x11 Hexadecimal 11, decimal value 17.This example shows the difference:$ gawk ’BEGIN { printf "%d, %d, %d\n", 011, 11, 0x11 }’⊣ 9, 11, 17Being able to use octal and hexadecimal constants in your programs is most usefulwhen working with data that cannot be represented conveniently as characters or as regularnumbers, such as binary data of various sorts.gawk allows the use of octal and hexadecimal constants in your program text. However,such numbers in the input data are not treated differently; doing so by default would breakold programs. (If you really need to do this, use the ‘--non-decimal-data’ commandlineoption; see Section 10.1 [Allowing Nondecimal Input Data], page 169.) If you haveoctal or hexadecimal data, you can use the strtonum function (see Section 8.1.3 [String-Manipulation Functions], page 132) to convert the data into a number. Most of the time,you will want to use octal or hexadecimal constants when working with the built-in bitmanipulation functions; see Section 8.1.6 [Bit-Manipulation Functions of gawk], page 150,for more information.Unlike some early C implementations, ‘8’ and ‘9’ are not valid in octal constants; e.g.,gawk treats ‘018’ as decimal 18:$ gawk ’BEGIN { print "021 is", 021 ; print 018 }’⊣ 021 is 17⊣ 18Octal and hexadecimal source code constants are a gawk extension. If gawk is in compatibilitymode (see Section 11.2 [Command-Line Options], page 177), they are not available.Advanced Notes: A Constant’s Base Does Not Affect Its ValueOnce a numeric constant has been converted internally into a number, gawk no longerremembers what the original form of the constant was; the internal value is always used.This has particular consequences for conversion of numbers to strings:$ gawk ’BEGIN { printf "0x11 is \n", 0x11 }’⊣ 0x11 is 5.1.3 Regular Expression ConstantsA regexp constant is a regular expression description enclosed in slashes, such as/^beginning and end$/. Most regexps used in awk programs are constant, but the ‘~’ and‘!~’ matching operators can also match computed or “dynamic” regexps (which are justordinary strings or variables that contain a regexp).5.2 Using Regular Expression ConstantsWhen used on the righthand side of the ‘~’ or ‘!~’ operators, a regexp constant merelystands for the regexp that is to be matched. However, regexp constants (such as /foo/)may be used like simple expressions. When a regexp constant appears by itself, it has

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

Saved successfully!

Ooh no, something went wrong!