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 7: Arrays in awk 1274 3 2 15 4 3 26 5 4 31 6 5 42 1 6 53 2 1 67.10 Scanning Multidimensional ArraysThere is no special for statement for scanning a “multidimensional” array. There cannotbe one, because, in truth, there are no multidimensional arrays or elements—there is onlya multidimensional way of accessing an array.However, if your program has an array that is always accessed as multidimensional, youcan get the effect of scanning it by combining the scanning for statement (see Section 7.5[Scanning All Elements of an Array], page 122) with the built-in split function (seeSection 8.1.3 [String-Manipulation Functions], page 132). It works in the following manner:for (combined in array) {split(combined, separate, SUBSEP)...}This sets the variable combined to each concatenated combined index in the array, andsplits it into the individual indices by breaking it apart where the value of SUBSEP appears.The individual indices then become the elements of the array separate.Thus, if a value is previously stored in array[1, "foo"]; then an element with index"1\034foo" exists in array. (Recall that the default value of SUBSEP is the character withcode 034.) Sooner or later, the for statement finds that index and does an iteration withthe variable combined set to "1\034foo". Then the split function is called as follows:split("1\034foo", separate, "\034")The result is to set separate[1] to "1" and separate[2] to "foo". Presto! The originalsequence of separate indices is recovered.7.11 Sorting Array Values and Indices with gawkThe order in which an array is scanned with a ‘for (i in array)’ loop is essentially arbitrary.In most awk implementations, sorting an array requires writing a sort function.While this can be educational for exploring different sorting algorithms, usually that’s notthe point of the program. gawk provides the built-in asort and asorti functions (seeSection 8.1.3 [String-Manipulation Functions], page 132) for sorting arrays. For example:populate the array datan = asort(data)for (i = 1; i

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

Saved successfully!

Ooh no, something went wrong!