1 1 8.5 Multidimensional Arrays 1 =========================== 1
1 · Multiscanning Scanning multidimensional arrays. 1 1 A "multidimensional array" is an array in which an element is identified 1 by a sequence of indices instead of a single index. For example, a 1 two-dimensional array requires two indices. The usual way (in many 1 languages, including 'awk') to refer to an element of a two-dimensional 1 array named 'grid' is with 'grid[X,Y]'. 1 1 Multidimensional arrays are supported in 'awk' through concatenation 1 of indices into one string. 'awk' converts the indices into strings 1 (⇒Conversion) and concatenates them together, with a separator 1 between them. This creates a single string that describes the values of 1 the separate indices. The combined string is used as a single index 1 into an ordinary, one-dimensional array. The separator used is the 1 value of the built-in variable 'SUBSEP'. 1 1 For example, suppose we evaluate the expression 'foo[5,12] = "value"' 1 when the value of 'SUBSEP' is '"@"'. The numbers 5 and 12 are converted 1 to strings and concatenated with an '@' between them, yielding '"5@12"'; 1 thus, the array element 'foo["5@12"]' is set to '"value"'. 1 1 Once the element's value is stored, 'awk' has no record of whether it 1 was stored with a single index or a sequence of indices. The two 1 expressions 'foo[5,12]' and 'foo[5 SUBSEP 12]' are always equivalent. 1 1 The default value of 'SUBSEP' is the string '"\034"', which contains 1 a nonprinting character that is unlikely to appear in an 'awk' program 1 or in most input data. The usefulness of choosing an unlikely character 1 comes from the fact that index values that contain a string matching 1 'SUBSEP' can lead to combined strings that are ambiguous. Suppose that 1 'SUBSEP' is '"@"'; then 'foo["a@b", "c"]' and 'foo["a", "b@c"]' are 1 indistinguishable because both are actually stored as 'foo["a@b@c"]'. 1 1 To test whether a particular index sequence exists in a 1 multidimensional array, use the same operator ('in') that is used for 1 single-dimensional arrays. Write the whole sequence of indices in 1 parentheses, separated by commas, as the left operand: 1 1 if ((SUBSCRIPT1, SUBSCRIPT2, ...) in ARRAY) 1 ... 1 1 Here is an example that treats its input as a two-dimensional array 1 of fields; it rotates this array 90 degrees clockwise and prints the 1 result. It assumes that all lines have the same number of elements: 1 1 { 1 if (max_nf < NF) 1 max_nf = NF 1 max_nr = NR 1 for (x = 1; x <= NF; x++) 1 vector[x, NR] = $x 1 } 1 1 END { 1 for (x = 1; x <= max_nf; x++) { 1 for (y = max_nr; y >= 1; --y) 1 printf("%s ", vector[x, y]) 1 printf("\n") 1 } 1 } 1 1 When given the input: 1 1 1 2 3 4 5 6 1 2 3 4 5 6 1 1 3 4 5 6 1 2 1 4 5 6 1 2 3 1 1 the program produces the following output: 1 1 4 3 2 1 1 5 4 3 2 1 6 5 4 3 1 1 6 5 4 1 2 1 6 5 1 3 2 1 6 1