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.

124 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>delete arrayThis ability is a gawk extension; it is not available in compatibility mode (see Section 11.2[Command-Line Options], page 177).Using this version of the delete statement is about three times more efficient than theequivalent loop that deletes each element one at a time.The following statement provides a portable but nonobvious way to clear out an array: 1split("", array)The split function (see Section 8.1.3 [String-Manipulation Functions], page 132) clearsout the target array first. This call asks it to split apart the null string. Because there isno data to split out, the function simply clears the array and then returns.Caution: Deleting an array does not change its type; you cannot delete an array andthen use the array’s name as a scalar (i.e., a regular variable). For example, the followingdoes not work:a[1] = 3; delete a; a = 37.7 Using Numbers to Subscript ArraysAn important aspect about arrays to remember is that array subscripts are always strings.When a numeric value is used as a subscript, it is converted to a string value before beingused for subscripting (see Section 5.4 [Conversion of Strings and Numbers], page 79). Thismeans that the value of the built-in variable CONVFMT can affect how your program accesseselements of an array. For example:xyz = 12.153data[xyz] = 1CONVFMT = "%2.2f"if (xyz in data)printf "%s is in data\n", xyzelseprintf "%s is not in data\n", xyzThis prints ‘12.15 is not in data’. The first statement gives xyz a numeric value. Assigningto data[xyz] subscripts data with the string value "12.153" (using the defaultconversion value of CONVFMT, "%.6g"). Thus, the array element data["12.153"] is assignedthe value one. The program then changes the value of CONVFMT. The test ‘(xyz indata)’ generates a new string value from xyz—this time "12.15"—because the value ofCONVFMT only allows two significant digits. This test fails, since "12.15" is a different stringfrom "12.153".According to the rules for conversions (see Section 5.4 [Conversion of Strings and Numbers],page 79), integer values are always converted to strings as integers, no matter whatthe value of CONVFMT may happen to be. So the usual case of the following works:for (i = 1; i

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

Saved successfully!

Ooh no, something went wrong!