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.

Chapter 7: Arrays in awk 121that have been deleted (see Section 7.6 [The delete Statement], page 123). Such a referenceautomatically creates that array element, with the null string as its value. (In some cases,this is unfortunate, because it might waste memory inside awk.)To determine whether an element exists in an array at a certain index, use the followingexpression:ind in arrayThis expression tests whether the particular index ind exists, without the side effect of creatingthat element if it is not present. The expression has the value one (true) if array[ind]exists and zero (false) if it does not exist. For example, this statement tests whether thearray frequencies contains the index ‘2’:if (2 in frequencies)print "Subscript 2 is present."Note that this is not a test of whether the array frequencies contains an element whosevalue is two. There is no way to do that except to scan all the elements. Also, this doesnot create frequencies[2], while the following (incorrect) alternative does:if (frequencies[2] != "")print "Subscript 2 is present."7.3 Assigning Array ElementsArray elements can be assigned values just like awk variables:array[index-expression] = valuearray is the name of an array. The expression index-expression is the index of the elementof the array that is assigned a value. The expression value is the value to assign to thatelement of the array.7.4 Basic Array ExampleThe following program takes a list of lines, each beginning with a line number, and printsthem out in order of line number. The line numbers are not in order when they are firstread—instead they are scrambled. This program sorts the lines by making an array usingthe line numbers as subscripts. The program then prints out the lines in sorted order oftheir numbers. It is a very simple program and gets confused upon encountering repeatednumbers, gaps, or lines that don’t begin with a number:{if ($1 > max)max = $1arr[$1] = $0}END {for (x = 1; x

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

Saved successfully!

Ooh no, something went wrong!