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.

120 <strong>G<strong>AWK</strong></strong>: <strong>Effective</strong> <strong>AWK</strong> <strong>Programming</strong>Element 3 Value 30Element 1 Value "foo"Element 0 Value 8Element 2 Value ""The pairs are shown in jumbled order because their order is irrelevant.One advantage of associative arrays is that new pairs can be added at any time. Forexample, suppose a tenth element is added to the array whose value is "number ten". Theresult is:Element 10 Value "number ten"Element 3 Value 30Element 1 Value "foo"Element 0 Value 8Element 2 Value ""Now the array is sparse, which just means some indices are missing. It has elements 0–3and 10, but doesn’t have elements 4, 5, 6, 7, 8, or 9.Another consequence of associative arrays is that the indices don’t have to be positiveintegers. Any number, or even a string, can be an index. For example, the following is anarray that translates words from English to French:Element "dog" Value "chien"Element "cat" Value "chat"Element "one" Value "un"Element 1 Value "un"Here we decided to translate the number one in both spelled-out and numeric form—thusillustrating that a single array can have both numbers and strings as indices. In fact,array subscripts are always strings; this is discussed in more detail in Section 7.7 [UsingNumbers to Subscript Arrays], page 124. Here, the number 1 isn’t double-quoted, since awkautomatically converts it to a string.The value of IGNORECASE has no effect upon array subscripting. The identical stringvalue used to store an array element must be used to retrieve it. When awk creates anarray (e.g., with the split built-in function), that array’s indices are consecutive integersstarting at one. (See Section 8.1.3 [String-Manipulation Functions], page 132.)awk’s arrays are efficient—the time to access an element is independent of the numberof elements in the array.7.2 Referring to an Array ElementThe principal way to use an array is to refer to one of its elements. An array reference isan expression as follows:array[index-expression]Here, array is the name of an array. The expression index-expression is the index of thedesired element of the array.The value of the array reference is the current value of that array element. For example,foo[4.3] is an expression for the element of array foo at index ‘4.3’.A reference to an array element that has no recorded value yields a value of "", the nullstring. This includes elements that have not been assigned any value as well as elements

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

Saved successfully!

Ooh no, something went wrong!