gawk: Numeric Array Subscripts
1
1 8.2 Using Numbers to Subscript Arrays
1 =====================================
1
1 An important aspect to remember about arrays is that _array subscripts
1 are always strings_. When a numeric value is used as a subscript, it is
11 converted to a string value before being used for subscripting (⇒
Conversion). This means that the value of the predefined variable
1 'CONVFMT' can affect how your program accesses elements of an array.
1 For example:
1
1 xyz = 12.153
1 data[xyz] = 1
1 CONVFMT = "%2.2f"
1 if (xyz in data)
1 printf "%s is in data\n", xyz
1 else
1 printf "%s is not in data\n", xyz
1
1 This prints '12.15 is not in data'. The first statement gives 'xyz' a
1 numeric value. Assigning to 'data[xyz]' subscripts 'data' with the
1 string value '"12.153"' (using the default conversion value of
1 'CONVFMT', '"%.6g"'). Thus, the array element 'data["12.153"]' is
1 assigned the value one. The program then changes the value of
1 'CONVFMT'. The test '(xyz in data)' generates a new string value from
1 'xyz'--this time '"12.15"'--because the value of 'CONVFMT' only allows
1 two significant digits. This test fails, because '"12.15"' is different
1 from '"12.153"'.
1
1 According to the rules for conversions (⇒Conversion), integer
1 values always convert to strings as integers, no matter what the value
1 of 'CONVFMT' may happen to be. So the usual case of the following
1 works:
1
1 for (i = 1; i <= maxsub; i++)
1 do something with array[i]
1
1 The "integer values always convert to strings as integers" rule has
1 an additional consequence for array indexing. Octal and hexadecimal
1 constants (⇒Nondecimal-numbers) are converted internally into
1 numbers, and their original form is forgotten. This means, for example,
1 that 'array[17]', 'array[021]', and 'array[0x11]' all refer to the same
1 element!
1
1 As with many things in 'awk', the majority of the time things work as
1 you would expect them to. But it is useful to have a precise knowledge
1 of the actual rules, as they can sometimes have a subtle effect on your
1 programs.
1