home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / unix / volume22 / gawk2.11 / part03 / gawk.texinfo.04
Text File  |  1990-06-07  |  50KB  |  1,401 lines

  1. often necessary to insure that it happens where you want it to by
  2. enclosing the items to be concatenated in parentheses.  For example, the
  3. following code fragment does not concatenate @code{file} and @code{name}
  4. as you might expect:
  5.  
  6. @example
  7. file = "file"
  8. name = "name"
  9. print "something meaningful" > file name
  10. @end example
  11.  
  12. @noindent
  13. It is necessary to use the following:
  14.  
  15. @example
  16. print "something meaningful" > (file name)
  17. @end example
  18.  
  19. We recommend you use parentheses around concatenation in all but the
  20. most common contexts (such as in the right-hand operand of @samp{=}).
  21.  
  22. @ignore
  23. @code{gawk} actually now allows a concatenation on the right hand
  24. side of a @code{>} redirection, but other @code{awk}s don't.  So for
  25. now we won't mention that fact.
  26. @end ignore
  27.  
  28. @node Comparison Ops, Boolean Ops, Concatenation, Expressions
  29. @section Comparison Expressions
  30. @cindex comparison expressions
  31. @cindex expressions, comparison
  32. @cindex relational operators
  33. @cindex operators, relational
  34. @cindex regexp operators
  35.  
  36. @dfn{Comparison expressions} compare strings or numbers for
  37. relationships such as equality.  They are written using @dfn{relational
  38. operators}, which are a superset of those in C.  Here is a table of
  39. them:
  40.  
  41. @table @code
  42. @item @var{x} < @var{y}
  43. True if @var{x} is less than @var{y}.
  44.  
  45. @item @var{x} <= @var{y}
  46. True if @var{x} is less than or equal to @var{y}.
  47.  
  48. @item @var{x} > @var{y}
  49. True if @var{x} is greater than @var{y}.
  50.  
  51. @item @var{x} >= @var{y}
  52. True if @var{x} is greater than or equal to @var{y}.
  53.  
  54. @item @var{x} == @var{y}
  55. True if @var{x} is equal to @var{y}.
  56.  
  57. @item @var{x} != @var{y}
  58. True if @var{x} is not equal to @var{y}.
  59.  
  60. @item @var{x} ~ @var{y}
  61. True if the string @var{x} matches the regexp denoted by @var{y}.
  62.  
  63. @item @var{x} !~ @var{y}
  64. True if the string @var{x} does not match the regexp denoted by @var{y}.
  65.  
  66. @item @var{subscript} in @var{array}
  67. True if array @var{array} has an element with the subscript @var{subscript}.
  68. @end table
  69.  
  70. Comparison expressions have the value 1 if true and 0 if false.
  71.  
  72. The operands of a relational operator are compared as numbers if they
  73. are both numbers.  Otherwise they are converted to, and compared as,
  74. strings (@pxref{Conversion}).  Strings are compared by comparing the
  75. first character of each, then the second character of each, and so on.
  76. Thus, @code{"10"} is less than @code{"9"}.
  77.  
  78. For example,
  79.  
  80. @example
  81. $1 == "foo"
  82. @end example
  83.  
  84. @noindent
  85. has the value of 1, or is true, if the first field of the current input
  86. record is precisely @samp{foo}.  By contrast, 
  87.  
  88. @example
  89. $1 ~ /foo/
  90. @end example
  91.  
  92. @noindent
  93. has the value 1 if the first field contains @samp{foo}.
  94.  
  95. The right hand operand of the @samp{~} and @samp{!~} operators may be
  96. either a constant regexp (@code{/@dots{}/}), or it may be an ordinary
  97. expression, in which case the value of the expression as a string is a
  98. dynamic regexp (@pxref{Regexp Usage}).
  99.  
  100. @cindex regexp as expression
  101. In very recent implementations of @code{awk}, a constant regular
  102. expression in slashes by itself is also an expression.  The regexp
  103. @code{/@var{regexp}/} is an abbreviation for this comparison expression:
  104.  
  105. @example
  106. $0 ~ /@var{regexp}/
  107. @end example
  108.  
  109. In some contexts it may be necessary to write parentheses around the
  110. regexp to avoid confusing the @code{gawk} parser.  For example,
  111. @code{(/x/ - /y/) > threshold} is not allowed, but @code{((/x/) - (/y/))
  112. > threshold} parses properly.
  113.  
  114. One special place where @code{/foo/} is @emph{not} an abbreviation for
  115. @code{$0 ~ /foo/} is when it is the right-hand operand of @samp{~} or
  116. @samp{!~}!
  117.  
  118. @node Boolean Ops, Assignment Ops, Comparison Ops, Expressions
  119. @section Boolean Expressions
  120. @cindex expressions, boolean
  121. @cindex boolean expressions
  122. @cindex operators, boolean
  123. @cindex boolean operators
  124. @cindex logical operations
  125. @cindex and operator
  126. @cindex or operator
  127. @cindex not operator
  128.  
  129. A @dfn{boolean expression} is combination of comparison expressions or
  130. matching expressions, using the @dfn{boolean operators} ``or''
  131. (@samp{||}), ``and'' (@samp{&&}), and ``not'' (@samp{!}), along with
  132. parentheses to control nesting.  The truth of the boolean expression is
  133. computed by combining the truth values of the component expressions.
  134.  
  135. Boolean expressions can be used wherever comparison and matching
  136. expressions can be used.  They can be used in @code{if} and @code{while}
  137. statements.  They have numeric values (1 if true, 0 if false), which
  138. come into place if the result of the boolean expression is stored in a
  139. variable, or used in arithmetic.
  140.  
  141. In addition, every boolean expression is also a valid boolean pattern, so
  142. you can use it as a pattern to control the execution of rules.
  143.  
  144. Here are descriptions of the three boolean operators, with an example of
  145. each.  It may be instructive to compare these examples with the
  146. analogous examples of boolean patterns (@pxref{Boolean Patterns}), which
  147. use the same boolean operators in patterns instead of expressions.
  148.  
  149. @table @code
  150. @item @var{boolean1} && @var{boolean2}
  151. True if both @var{boolean1} and @var{boolean2} are true.  For example,
  152. the following statement prints the current input record if it contains
  153. both @samp{2400} and @samp{foo}.@refill
  154.  
  155. @example
  156. if ($0 ~ /2400/ && $0 ~ /foo/) print
  157. @end example
  158.  
  159. The subexpression @var{boolean2} is evaluated only if @var{boolean1}
  160. is true.  This can make a difference when @var{boolean2} contains
  161. expressions that have side effects: in the case of @code{$0 ~ /foo/ &&
  162. ($2 == bar++)}, the variable @code{bar} is not incremented if there is
  163. no @samp{foo} in the record.
  164.  
  165. @item @var{boolean1} || @var{boolean2}
  166. True if at least one of @var{boolean1} and @var{boolean2} is true.
  167. For example, the following command prints all records in the input
  168. file @file{BBS-list} that contain @emph{either} @samp{2400} or
  169. @samp{foo}, or both.@refill
  170.  
  171. @example
  172. awk '@{ if ($0 ~ /2400/ || $0 ~ /foo/) print @}' BBS-list
  173. @end example
  174.  
  175. The subexpression @var{boolean2} is evaluated only if @var{boolean1}
  176. is false.  This can make a difference when @var{boolean2} contains
  177. expressions that have side effects.
  178.  
  179. @item !@var{boolean}
  180. True if @var{boolean} is false.  For example, the following program prints
  181. all records in the input file @file{BBS-list} that do @emph{not} contain the
  182. string @samp{foo}.
  183.  
  184. @example
  185. awk '@{ if (! ($0 ~ /foo/)) print @}' BBS-list
  186. @end example
  187. @end table
  188.  
  189. @node Assignment Ops, Increment Ops, Boolean Ops, Expressions
  190. @section Assignment Expressions
  191. @cindex assignment operators
  192. @cindex operators, assignment
  193. @cindex expressions, assignment
  194.  
  195. An @dfn{assignment} is an expression that stores a new value into a
  196. variable.  For example, let's assign the value 1 to the variable
  197. @code{z}:@refill
  198.  
  199. @example
  200. z = 1
  201. @end example
  202.  
  203. After this expression is executed, the variable @code{z} has the value 1.
  204. Whatever old value @code{z} had before the assignment is forgotten.
  205.  
  206. Assignments can store string values also.  For example, this would store
  207. the value @code{"this food is good"} in the variable @code{message}:
  208.  
  209. @example
  210. thing = "food"
  211. predicate = "good"
  212. message = "this " thing " is " predicate
  213. @end example
  214.  
  215. @noindent
  216. (This also illustrates concatenation of strings.)
  217.  
  218. The @samp{=} sign is called an @dfn{assignment operator}.  It is the
  219. simplest assignment operator because the value of the right-hand
  220. operand is stored unchanged.
  221.  
  222. @cindex side effect
  223. Most operators (addition, concatenation, and so on) have no effect
  224. except to compute a value.  If you ignore the value, you might as well
  225. not use the operator.  An assignment operator is different; it does
  226. produce a value, but even if you ignore the value, the assignment still
  227. makes itself felt through the alteration of the variable.  We call this
  228. a @dfn{side effect}.
  229.  
  230. @cindex lvalue
  231. The left-hand operand of an assignment need not be a variable
  232. (@pxref{Variables}); it can also be a field (@pxref{Changing Fields}) or
  233. an array element (@pxref{Arrays}).  These are all called @dfn{lvalues},
  234. which means they can appear on the left-hand side of an assignment operator.
  235. The right-hand operand may be any expression; it produces the new value
  236. which the assignment stores in the specified variable, field or array
  237. element.
  238.  
  239. It is important to note that variables do @emph{not} have permanent types.
  240. The type of a variable is simply the type of whatever value it happens
  241. to hold at the moment.  In the following program fragment, the variable
  242. @code{foo} has a numeric value at first, and a string value later on:
  243.  
  244. @example
  245. foo = 1
  246. print foo
  247. foo = "bar"
  248. print foo
  249. @end example
  250.  
  251. @noindent
  252. When the second assignment gives @code{foo} a string value, the fact that
  253. it previously had a numeric value is forgotten.
  254.  
  255. An assignment is an expression, so it has a value: the same value that
  256. is assigned.  Thus, @code{z = 1} as an expression has the value 1.
  257. One consequence of this is that you can write multiple assignments together:
  258.  
  259. @example
  260. x = y = z = 0
  261. @end example
  262.  
  263. @noindent
  264. stores the value 0 in all three variables.  It does this because the
  265. value of @code{z = 0}, which is 0, is stored into @code{y}, and then
  266. the value of @code{y = z = 0}, which is 0, is stored into @code{x}.
  267.  
  268. You can use an assignment anywhere an expression is called for.  For
  269. example, it is valid to write @code{x != (y = 1)} to set @code{y} to 1
  270. and then test whether @code{x} equals 1.  But this style tends to make
  271. programs hard to read; except in a one-shot program, you should
  272. rewrite it to get rid of such nesting of assignments.  This is never very
  273. hard.
  274.  
  275. Aside from @samp{=}, there are several other assignment operators that
  276. do arithmetic with the old value of the variable.  For example, the
  277. operator @samp{+=} computes a new value by adding the right-hand value
  278. to the old value of the variable.  Thus, the following assignment adds
  279. 5 to the value of @code{foo}:
  280.  
  281. @example
  282. foo += 5
  283. @end example
  284.  
  285. @noindent
  286. This is precisely equivalent to the following:
  287.  
  288. @example
  289. foo = foo + 5
  290. @end example
  291.  
  292. @noindent
  293. Use whichever one makes the meaning of your program clearer.
  294.  
  295. Here is a table of the arithmetic assignment operators.  In each
  296. case, the right-hand operand is an expression whose value is converted
  297. to a number.
  298.  
  299. @table @code
  300. @item @var{lvalue} += @var{increment}
  301. Adds @var{increment} to the value of @var{lvalue} to make the new value
  302. of @var{lvalue}.
  303.  
  304. @item @var{lvalue} -= @var{decrement}
  305. Subtracts @var{decrement} from the value of @var{lvalue}.
  306.  
  307. @item @var{lvalue} *= @var{coefficient}
  308. Multiplies the value of @var{lvalue} by @var{coefficient}.
  309.  
  310. @item @var{lvalue} /= @var{quotient}
  311. Divides the value of @var{lvalue} by @var{quotient}.
  312.  
  313. @item @var{lvalue} %= @var{modulus}
  314. Sets @var{lvalue} to its remainder by @var{modulus}.
  315.  
  316. @item @var{lvalue} ^= @var{power}
  317. @itemx @var{lvalue} **= @var{power}
  318. Raises @var{lvalue} to the power @var{power}.
  319. @end table
  320.  
  321. @node Increment Ops, Conversion, Assignment Ops, Expressions
  322. @section Increment Operators
  323.  
  324. @cindex increment operators
  325. @cindex operators, increment
  326. @dfn{Increment operators} increase or decrease the value of a variable
  327. by 1.  You could do the same thing with an assignment operator, so
  328. the increment operators add no power to the @code{awk} language; but they
  329. are convenient abbreviations for something very common.
  330.  
  331. The operator to add 1 is written @samp{++}.  It can be used to increment
  332. a variable either before or after taking its value.
  333.  
  334. To pre-increment a variable @var{v}, write @code{++@var{v}}.  This adds
  335. 1 to the value of @var{v} and that new value is also the value of this
  336. expression.  The assignment expression @code{@var{v} += 1} is completely
  337. equivalent.
  338.  
  339. Writing the @samp{++} after the variable specifies post-increment.  This
  340. increments the variable value just the same; the difference is that the
  341. value of the increment expression itself is the variable's @emph{old}
  342. value.  Thus, if @code{foo} has value 4, then the expression @code{foo++}
  343. has the value 4, but it changes the value of @code{foo} to 5.
  344.  
  345. The post-increment @code{foo++} is nearly equivalent to writing @code{(foo
  346. += 1) - 1}.  It is not perfectly equivalent because all numbers in
  347. @code{awk} are floating point: in floating point, @code{foo + 1 - 1} does
  348. not necessarily equal @code{foo}.  But the difference is minute as
  349. long as you stick to numbers that are fairly small (less than a trillion).
  350.  
  351. Any lvalue can be incremented.  Fields and array elements are incremented
  352. just like variables.
  353.  
  354. The decrement operator @samp{--} works just like @samp{++} except that
  355. it subtracts 1 instead of adding.  Like @samp{++}, it can be used before
  356. the lvalue to pre-decrement or after it to post-decrement.
  357.  
  358. Here is a summary of increment and decrement expressions.
  359.  
  360. @table @code
  361. @item ++@var{lvalue}
  362. This expression increments @var{lvalue} and the new value becomes the
  363. value of this expression.
  364.  
  365. @item @var{lvalue}++
  366. This expression causes the contents of @var{lvalue} to be incremented.
  367. The value of the expression is the @emph{old} value of @var{lvalue}.
  368.  
  369. @item --@var{lvalue}
  370. Like @code{++@var{lvalue}}, but instead of adding, it subtracts.  It
  371. decrements @var{lvalue} and delivers the value that results.
  372.  
  373. @item @var{lvalue}--
  374. Like @code{@var{lvalue}++}, but instead of adding, it subtracts.  It
  375. decrements @var{lvalue}.  The value of the expression is the @emph{old}
  376. value of @var{lvalue}.
  377. @end table
  378.  
  379. @node Conversion, Conditional Exp, Increment Ops, Expressions
  380. @section Conversion of Strings and Numbers
  381.  
  382. @cindex conversion of strings and numbers
  383. Strings are converted to numbers, and numbers to strings, if the context
  384. of the @code{awk} program demands it.  For example, if the value of
  385. either @code{foo} or @code{bar} in the expression @code{foo + bar}
  386. happens to be a string, it is converted to a number before the addition
  387. is performed.  If numeric values appear in string concatenation, they
  388. are converted to strings.  Consider this:@refill
  389.  
  390. @example
  391. two = 2; three = 3
  392. print (two three) + 4
  393. @end example
  394.  
  395. @noindent
  396. This eventually prints the (numeric) value 27.  The numeric values of
  397. the variables @code{two} and @code{three} are converted to strings and
  398. concatenated together, and the resulting string is converted back to the
  399. number 23, to which 4 is then added.
  400.  
  401. If, for some reason, you need to force a number to be converted to a
  402. string, concatenate the null string with that number.  To force a string
  403. to be converted to a number, add zero to that string.
  404.  
  405. Strings are converted to numbers by interpreting them as numerals:
  406. @code{"2.5"} converts to 2.5, and @code{"1e3"} converts to 1000.
  407. Strings that can't be interpreted as valid numbers are converted to
  408. zero.
  409.  
  410. @vindex OFMT
  411. The exact manner in which numbers are converted into strings is controlled
  412. by the @code{awk} built-in variable @code{OFMT} (@pxref{Built-in Variables}).
  413. Numbers are converted using a special
  414. version of the @code{sprintf} function (@pxref{Built-in}) with @code{OFMT}
  415. as the format specifier.@refill
  416.  
  417. @code{OFMT}'s default value is @code{"%.6g"}, which prints a value with
  418. at least six significant digits.  For some applications you will want to
  419. change it to specify more precision.  Double precision on most modern
  420. machines gives you 16 or 17 decimal digits of precision.
  421.  
  422. Strange results can happen if you set @code{OFMT} to a string that doesn't
  423. tell @code{sprintf} how to format floating point numbers in a useful way.
  424. For example, if you forget the @samp{%} in the format, all numbers will be
  425. converted to the same constant string.@refill
  426.  
  427. @node Conditional Exp, Function Calls, Conversion, Expressions
  428. @section Conditional Expressions
  429. @cindex conditional expression
  430. @cindex expression, conditional
  431.  
  432. A @dfn{conditional expression} is a special kind of expression with
  433. three operands.  It allows you to use one expression's value to select
  434. one of two other expressions.
  435.  
  436. The conditional expression looks the same as in the C language:
  437.  
  438. @example
  439. @var{selector} ? @var{if-true-exp} : @var{if-false-exp}
  440. @end example
  441.  
  442. @noindent
  443. There are three subexpressions.  The first, @var{selector}, is always
  444. computed first.  If it is ``true'' (not zero) then @var{if-true-exp} is
  445. computed next and its value becomes the value of the whole expression.
  446. Otherwise, @var{if-false-exp} is computed next and its value becomes the
  447. value of the whole expression.
  448.  
  449. For example, this expression produces the absolute value of @code{x}:
  450.  
  451. @example
  452. x > 0 ? x : -x
  453. @end example
  454.  
  455. Each time the conditional expression is computed, exactly one of
  456. @var{if-true-exp} and @var{if-false-exp} is computed; the other is ignored.
  457. This is important when the expressions contain side effects.  For example,
  458. this conditional expression examines element @code{i} of either array
  459. @code{a} or array @code{b}, and increments @code{i}.
  460.  
  461. @example
  462. x == y ? a[i++] : b[i++]
  463. @end example
  464.  
  465. @noindent
  466. This is guaranteed to increment @code{i} exactly once, because each time
  467. one or the other of the two increment expressions is executed,
  468. and the other is not.
  469.  
  470. @node Function Calls, Precedence, Conditional Exp, Expressions
  471. @section Function Calls
  472. @cindex function call
  473. @cindex calling a function
  474.  
  475. A @dfn{function} is a name for a particular calculation.  Because it has
  476. a name, you can ask for it by name at any point in the program.  For
  477. example, the function @code{sqrt} computes the square root of a number.
  478.  
  479. A fixed set of functions are @dfn{built in}, which means they are
  480. available in every @code{awk} program.  The @code{sqrt} function is one
  481. of these.  @xref{Built-in}, for a list of built-in functions and their
  482. descriptions.  In addition, you can define your own functions in the
  483. program for use elsewhere in the same program.  @xref{User-defined},
  484. for how to do this.
  485.  
  486. @cindex arguments in function call
  487. The way to use a function is with a @dfn{function call} expression,
  488. which consists of the function name followed by a list of
  489. @dfn{arguments} in parentheses.  The arguments are expressions which
  490. give the raw materials for the calculation that the function will do.
  491. When there is more than one argument, they are separated by commas.  If
  492. there are no arguments, write just @samp{()} after the function name.
  493. Here are some examples:
  494.  
  495. @example
  496. sqrt(x**2 + y**2)    # @r{One argument}
  497. atan2(y, x)          # @r{Two arguments}
  498. rand()               # @r{No arguments}
  499. @end example
  500.  
  501. @strong{Do not put any space between the function name and the
  502. open-parenthesis!}  A user-defined function name looks just like the name of
  503. a variable, and space would make the expression look like concatenation
  504. of a variable with an expression inside parentheses.  Space before the
  505. parenthesis is harmless with built-in functions, but it is best not to get
  506. into the habit of using space, lest you do likewise for a user-defined
  507. function one day by mistake.
  508.  
  509. Each function expects a particular number of arguments.  For example, the
  510. @code{sqrt} function must be called with a single argument, the number
  511. to take the square root of:
  512.  
  513. @example
  514. sqrt(@var{argument})
  515. @end example
  516.  
  517. Some of the built-in functions allow you to omit the final argument.
  518. If you do so, they use a reasonable default.  @xref{Built-in},
  519. for full details.  If arguments are omitted in calls to user-defined
  520. functions, then those arguments are treated as local variables,
  521. initialized to the null string (@pxref{User-defined}).
  522.  
  523. Like every other expression, the function call has a value, which is
  524. computed by the function based on the arguments you give it.  In this
  525. example, the value of @code{sqrt(@var{argument})} is the square root of the
  526. argument.  A function can also have side effects, such as assigning the
  527. values of certain variables or doing I/O.
  528.  
  529. Here is a command to read numbers, one number per line, and print the
  530. square root of each one:
  531.  
  532. @example
  533. awk '@{ print "The square root of", $1, "is", sqrt($1) @}'
  534. @end example
  535.  
  536. @node Precedence,, Function Calls, Expressions
  537. @section Operator Precedence: How Operators Nest
  538. @cindex precedence
  539. @cindex operator precedence
  540.  
  541. @dfn{Operator precedence} determines how operators are grouped, when
  542. different operators appear close by in one expression.  For example,
  543. @samp{*} has higher precedence than @samp{+}; thus, @code{a + b * c}
  544. means to multiply @code{b} and @code{c}, and then add @code{a} to the
  545. product.
  546.  
  547. You can overrule the precedence of the operators by writing parentheses
  548. yourself.  You can think of the precedence rules as saying where the
  549. parentheses are assumed if you do not write parentheses yourself.  In
  550. fact, it is wise always to use parentheses whenever you have an unusual
  551. combination of operators, because other people who read the program may
  552. not remember what the precedence is in this case.  You might forget,
  553. too; then you could make a mistake.  Explicit parentheses will prevent
  554. any such mistake.
  555.  
  556. When operators of equal precedence are used together, the leftmost
  557. operator groups first, except for the assignment, conditional and
  558. and exponentiation operators, which group in the opposite order.
  559. Thus, @code{a - b + c} groups as @code{(a - b) + c};
  560. @code{a = b = c} groups as @code{a = (b = c)}.
  561.  
  562. The precedence of prefix unary operators does not matter as long as only
  563. unary operators are involved, because there is only one way to parse
  564. them---innermost first.  Thus, @code{$++i} means @code{$(++i)} and
  565. @code{++$x} means @code{++($x)}.  However, when another operator follows
  566. the operand, then the precedence of the unary operators can matter.
  567. Thus, @code{$x**2} means @code{($x)**2}, but @code{-x**2} means
  568. @code{-(x**2)}, because @samp{-} has lower precedence than @samp{**}
  569. while @samp{$} has higher precedence.
  570.  
  571. Here is a table of the operators of @code{awk}, in order of increasing
  572. precedence:
  573.  
  574. @table @asis
  575. @item assignment
  576. @samp{=}, @samp{+=}, @samp{-=}, @samp{*=}, @samp{/=}, @samp{%=},
  577. @samp{^=}, @samp{**=}.  These operators group right-to-left.
  578.  
  579. @item conditional
  580. @samp{?:}.  These operators group right-to-left.
  581.  
  582. @item logical ``or''.
  583. @samp{||}.
  584.  
  585. @item logical ``and''.
  586. @samp{&&}.
  587.  
  588. @item array membership
  589. @code{in}.
  590.  
  591. @item matching
  592. @samp{~}, @samp{!~}.
  593.  
  594. @item relational, and redirection
  595. The relational operators and the redirections have the same precedence
  596. level.  Characters such as @samp{>} serve both as relationals and as
  597. redirections; the context distinguishes between the two meanings.
  598.  
  599. The relational operators are @samp{<}, @samp{<=}, @samp{==}, @samp{!=},
  600. @samp{>=} and @samp{>}.
  601.  
  602. The I/O redirection operators are @samp{<}, @samp{>}, @samp{>>} and
  603. @samp{|}.
  604.  
  605. Note that I/O redirection operators in @code{print} and @code{printf}
  606. statements belong to the statement level, not to expressions.  The
  607. redirection does not produce an expression which could be the operand of
  608. another operator.  As a result, it does not make sense to use a
  609. redirection operator near another operator of lower precedence, without
  610. parentheses.  Such combinations, for example @samp{print foo > a ? b :
  611. c}, result in syntax errors.
  612.  
  613. @item concatentation
  614. No special token is used to indicate concatenation.
  615. The operands are simply written side by side.
  616. @c This is supposedly being fixed
  617. @ignore
  618. Concatenation has the same precedence as relational and redirection
  619. operators.  These operators nest left to right.  Thus, @code{4 5 > 6}
  620. concatenates first, yielding 1, while @code{6 < 4 5} compares first, and
  621. yields @code{"05"}.
  622. @end ignore
  623.  
  624. @item add, subtract
  625. @samp{+}, @samp{-}.
  626.  
  627. @item multiply, divide, mod
  628. @samp{*}, @samp{/}, @samp{%}.
  629.  
  630. @item unary plus, minus, ``not''
  631. @samp{+}, @samp{-}, @samp{!}.
  632.  
  633. @item exponentiation
  634. @samp{^}, @samp{**}.  These operators group right-to-left.
  635.  
  636. @item increment, decrement
  637. @samp{++}, @samp{--}.
  638.  
  639. @item field
  640. @samp{$}.
  641. @end table
  642.  
  643. @node Statements, Arrays, Expressions, Top
  644. @chapter Actions: Control Statements
  645. @cindex control statement
  646.  
  647. @dfn{Control statements} such as @code{if}, @code{while}, and so on
  648. control the flow of execution in @code{awk} programs.  Most of the
  649. control statements in @code{awk} are patterned on similar statements in
  650. C.
  651.  
  652. All the control statements start with special keywords such as @code{if}
  653. and @code{while}, to distinguish them from simple expressions.
  654.  
  655. Many control statements contain other statements; for example, the
  656. @code{if} statement contains another statement which may or may not be
  657. executed.  The contained statement is called the @dfn{body}.  If you
  658. want to include more than one statement in the body, group them into a
  659. single compound statement with curly braces, separating them with
  660. newlines or semicolons.
  661.  
  662. @menu
  663. * If Statement::            Conditionally execute some @code{awk} statements.
  664.  
  665. * While Statement::         Loop until some condition is satisfied.
  666.  
  667. * Do Statement::            Do specified action while looping until some
  668.                             condition is satisfied.
  669.  
  670. * For Statement::           Another looping statement, that provides
  671.                             initialization and increment clauses.
  672.  
  673. * Break Statement::         Immediately exit the innermost enclosing loop.
  674.  
  675. * Continue Statement::      Skip to the end of the innermost enclosing loop.
  676.  
  677. * Next Statement::          Stop processing the current input record.
  678.  
  679. * Exit Statement::          Stop execution of @code{awk}.
  680. @end menu
  681.  
  682. @node If Statement, While Statement, Statements, Statements
  683. @section The @code{if} Statement
  684.  
  685. @cindex @code{if} statement
  686. The @code{if}-@code{else} statement is @code{awk}'s decision-making
  687. statement.  It looks like this:@refill
  688.  
  689. @example
  690. if (@var{condition}) @var{then-body} @r{[}else @var{else-body}@r{]}
  691. @end example
  692.  
  693. @noindent
  694. Here @var{condition} is an expression that controls what the rest of the
  695. statement will do.  If @var{condition} is true, @var{then-body} is
  696. executed; otherwise, @var{else-body} is executed (assuming that the
  697. @code{else} clause is present).  The @code{else} part of the statement is
  698. optional.  The condition is considered false if its value is zero or
  699. the null string, true otherwise.@refill
  700.  
  701. Here is an example:
  702.  
  703. @example
  704. if (x % 2 == 0)
  705.     print "x is even"
  706. else
  707.     print "x is odd"
  708. @end example
  709.  
  710. In this example, if the expression @code{x % 2 == 0} is true (that is,
  711. the value of @code{x} is divisible by 2), then the first @code{print}
  712. statement is executed, otherwise the second @code{print} statement is
  713. performed.@refill
  714.  
  715. If the @code{else} appears on the same line as @var{then-body}, and
  716. @var{then-body} is not a compound statement (i.e., not surrounded by
  717. curly braces), then a semicolon must separate @var{then-body} from
  718. @code{else}.  To illustrate this, let's rewrite the previous example:
  719.  
  720. @group
  721. @example
  722. awk '@{ if (x % 2 == 0) print "x is even"; else
  723.         print "x is odd" @}'
  724. @end example
  725. @end group
  726.  
  727. @noindent
  728. If you forget the @samp{;}, @code{awk} won't be able to parse the
  729. statement, and you will get a syntax error.
  730.  
  731. We would not actually write this example this way, because a human
  732. reader might fail to see the @code{else} if it were not the first thing
  733. on its line.
  734.  
  735. @node While Statement, Do Statement, If Statement, Statements
  736. @section The @code{while} Statement
  737. @cindex @code{while} statement
  738. @cindex loop
  739. @cindex body of a loop
  740.  
  741. In programming, a @dfn{loop} means a part of a program that is (or at least can
  742. be) executed two or more times in succession.
  743.  
  744. The @code{while} statement is the simplest looping statement in
  745. @code{awk}.  It repeatedly executes a statement as long as a condition is
  746. true.  It looks like this:
  747.  
  748. @example
  749. while (@var{condition})
  750.   @var{body}
  751. @end example
  752.  
  753. @noindent
  754. Here @var{body} is a statement that we call the @dfn{body} of the loop,
  755. and @var{condition} is an expression that controls how long the loop
  756. keeps running.
  757.  
  758. The first thing the @code{while} statement does is test @var{condition}.
  759. If @var{condition} is true, it executes the statement @var{body}.
  760. (Truth, as usual in @code{awk}, means that the value of @var{condition}
  761. is not zero and not a null string.)  After @var{body} has been executed,
  762. @var{condition} is tested again, and if it is still true, @var{body} is
  763. executed again.  This process repeats until @var{condition} is no longer
  764. true.  If @var{condition} is initially false, the body of the loop is
  765. never executed.@refill
  766.  
  767. This example prints the first three fields of each record, one per line.
  768.  
  769. @example
  770. awk '@{ i = 1
  771.        while (i <= 3) @{
  772.            print $i
  773.            i++
  774.        @}
  775. @}'
  776. @end example
  777.  
  778. @noindent
  779. Here the body of the loop is a compound statement enclosed in braces,
  780. containing two statements.
  781.  
  782. The loop works like this: first, the value of @code{i} is set to 1.
  783. Then, the @code{while} tests whether @code{i} is less than or equal to
  784. three.  This is the case when @code{i} equals one, so the @code{i}-th
  785. field is printed.  Then the @code{i++} increments the value of @code{i}
  786. and the loop repeats.  The loop terminates when @code{i} reaches 4.
  787.  
  788. As you can see, a newline is not required between the condition and the
  789. body; but using one makes the program clearer unless the body is a
  790. compound statement or is very simple.  The newline after the open-brace
  791. that begins the compound statement is not required either, but the
  792. program would be hard to read without it.
  793.  
  794. @node Do Statement, For Statement, While Statement, Statements
  795. @section The @code{do}-@code{while} Statement
  796.  
  797. The @code{do} loop is a variation of the @code{while} looping statement.
  798. The @code{do} loop executes the @var{body} once, then repeats @var{body}
  799. as long as @var{condition} is true.  It looks like this:
  800.  
  801. @group
  802. @example
  803. do
  804.   @var{body}
  805. while (@var{condition})
  806. @end example
  807. @end group
  808.  
  809. Even if @var{condition} is false at the start, @var{body} is executed at
  810. least once (and only once, unless executing @var{body} makes
  811. @var{condition} true).  Contrast this with the corresponding
  812. @code{while} statement:
  813.  
  814. @example
  815. while (@var{condition})
  816.   @var{body}
  817. @end example
  818.  
  819. @noindent
  820. This statement does not execute @var{body} even once if @var{condition}
  821. is false to begin with.
  822.  
  823. Here is an example of a @code{do} statement:
  824.  
  825. @example
  826. awk '@{ i = 1
  827.        do @{
  828.           print $0
  829.           i++
  830.        @} while (i <= 10)
  831. @}'
  832. @end example
  833.  
  834. @noindent
  835. prints each input record ten times.  It isn't a very realistic example,
  836. since in this case an ordinary @code{while} would do just as well.  But
  837. this reflects actual experience; there is only occasionally a real use
  838. for a @code{do} statement.@refill
  839.  
  840. @node For Statement, Break Statement, Do Statement, Statements
  841. @section The @code{for} Statement
  842. @cindex @code{for} statement
  843.  
  844. The @code{for} statement makes it more convenient to count iterations of a
  845. loop.  The general form of the @code{for} statement looks like this:@refill
  846.  
  847. @example
  848. for (@var{initialization}; @var{condition}; @var{increment})
  849.   @var{body}
  850. @end example
  851.  
  852. @noindent
  853. This statement starts by executing @var{initialization}.  Then, as long
  854. as @var{condition} is true, it repeatedly executes @var{body} and then
  855. @var{increment}.  Typically @var{initialization} sets a variable to
  856. either zero or one, @var{increment} adds 1 to it, and @var{condition}
  857. compares it against the desired number of iterations.
  858.  
  859. Here is an example of a @code{for} statement:
  860.  
  861. @example
  862. awk '@{ for (i = 1; i <= 3; i++)
  863.           print $i
  864. @}'
  865. @end example
  866.  
  867. @noindent
  868. This prints the first three fields of each input record, one field per
  869. line.
  870.  
  871. In the @code{for} statement, @var{body} stands for any statement, but
  872. @var{initialization}, @var{condition} and @var{increment} are just
  873. expressions.  You cannot set more than one variable in the
  874. @var{initialization} part unless you use a multiple assignment statement
  875. such as @code{x = y = 0}, which is possible only if all the initial values
  876. are equal.  (But you can initialize additional variables by writing
  877. their assignments as separate statements preceding the @code{for} loop.)
  878.  
  879. The same is true of the @var{increment} part; to increment additional
  880. variables, you must write separate statements at the end of the loop.
  881. The C compound expression, using C's comma operator, would be useful in
  882. this context, but it is not supported in @code{awk}.
  883.  
  884. Most often, @var{increment} is an increment expression, as in the
  885. example above.  But this is not required; it can be any expression
  886. whatever.  For example, this statement prints all the powers of 2
  887. between 1 and 100:
  888.  
  889. @example
  890. for (i = 1; i <= 100; i *= 2)
  891.   print i
  892. @end example
  893.  
  894. Any of the three expressions in the parentheses following @code{for} may
  895. be omitted if there is nothing to be done there.  Thus, @w{@samp{for (;x
  896. > 0;)}} is equivalent to @w{@samp{while (x > 0)}}.  If the
  897. @var{condition} is omitted, it is treated as @var{true}, effectively
  898. yielding an infinite loop.@refill
  899.  
  900. In most cases, a @code{for} loop is an abbreviation for a @code{while}
  901. loop, as shown here:
  902.  
  903. @example
  904. @var{initialization}
  905. while (@var{condition}) @{
  906.   @var{body}
  907.   @var{increment}
  908. @}
  909. @end example
  910.  
  911. @noindent
  912. The only exception is when the @code{continue} statement
  913. (@pxref{Continue Statement}) is used inside the loop; changing a
  914. @code{for} statement to a @code{while} statement in this way can change
  915. the effect of the @code{continue} statement inside the loop.
  916.  
  917. There is an alternate version of the @code{for} loop, for iterating over
  918. all the indices of an array:
  919.  
  920. @example
  921. for (i in array)
  922.     @var{do something with} array[i]
  923. @end example
  924.  
  925. @noindent
  926. @xref{Arrays}, for more information on this version of the @code{for} loop.
  927.  
  928. The @code{awk} language has a @code{for} statement in addition to a
  929. @code{while} statement because often a @code{for} loop is both less work to
  930. type and more natural to think of.  Counting the number of iterations is
  931. very common in loops.  It can be easier to think of this counting as part
  932. of looping rather than as something to do inside the loop.
  933.  
  934. The next section has more complicated examples of @code{for} loops.
  935.  
  936. @node Break Statement, Continue Statement, For Statement, Statements
  937. @section The @code{break} Statement
  938. @cindex @code{break} statement
  939. @cindex loops, exiting
  940.  
  941. The @code{break} statement jumps out of the innermost @code{for},
  942. @code{while}, or @code{do}-@code{while} loop that encloses it.  The
  943. following example finds the smallest divisor of any integer, and also
  944. identifies prime numbers:@refill
  945.  
  946. @example
  947. awk '# find smallest divisor of num
  948.      @{ num = $1
  949.        for (div = 2; div*div <= num; div++)
  950.          if (num % div == 0)
  951.            break
  952.        if (num % div == 0)
  953.          printf "Smallest divisor of %d is %d\n", num, div
  954.        else
  955.          printf "%d is prime\n", num  @}'
  956. @end example
  957.  
  958. When the remainder is zero in the first @code{if} statement, @code{awk}
  959. immediately @dfn{breaks out} of the containing @code{for} loop.  This means
  960. that @code{awk} proceeds immediately to the statement following the loop
  961. and continues processing.  (This is very different from the @code{exit}
  962. statement (@pxref{Exit Statement}) which stops the entire @code{awk}
  963. program.)@refill
  964.  
  965. Here is another program equivalent to the previous one.  It illustrates how
  966. the @var{condition} of a @code{for} or @code{while} could just as well be
  967. replaced with a @code{break} inside an @code{if}:
  968.  
  969. @example
  970. awk '# find smallest divisor of num
  971.      @{ num = $1
  972.        for (div = 2; ; div++) @{
  973.          if (num % div == 0) @{
  974.            printf "Smallest divisor of %d is %d\n", num, div
  975.            break
  976.          @}
  977.          if (div*div > num) @{
  978.            printf "%d is prime\n", num
  979.            break
  980.          @}
  981.        @}
  982. @}'
  983. @end example
  984.  
  985. @node Continue Statement, Next Statement, Break Statement, Statements
  986. @section The @code{continue} Statement
  987.  
  988. @cindex @code{continue} statement
  989. The @code{continue} statement, like @code{break}, is used only inside
  990. @code{for}, @code{while}, and @code{do}-@code{while} loops.  It skips
  991. over the rest of the loop body, causing the next cycle around the loop
  992. to begin immediately.  Contrast this with @code{break}, which jumps out
  993. of the loop altogether.  Here is an example:@refill
  994.  
  995. @example
  996. # print names that don't contain the string "ignore"
  997.  
  998. # first, save the text of each line
  999. @{ names[NR] = $0 @}
  1000.  
  1001. # print what we're interested in
  1002. END @{
  1003.    for (x in names) @{
  1004.        if (names[x] ~ /ignore/)
  1005.            continue
  1006.        print names[x]
  1007.    @}
  1008. @}
  1009. @end example
  1010.  
  1011. If one of the input records contains the string @samp{ignore}, this
  1012. example skips the print statement for that record, and continues back to
  1013. the first statement in the loop.
  1014.  
  1015. This isn't a practical example of @code{continue}, since it would be
  1016. just as easy to write the loop like this:
  1017.  
  1018. @example
  1019. for (x in names)
  1020.   if (names[x] !~ /ignore/)
  1021.     print names[x]
  1022. @end example
  1023.  
  1024. The @code{continue} statement in a @code{for} loop directs @code{awk} to
  1025. skip the rest of the body of the loop, and resume execution with the
  1026. increment-expression of the @code{for} statement.  The following program
  1027. illustrates this fact:@refill
  1028.  
  1029. @example
  1030. awk 'BEGIN @{
  1031.      for (x = 0; x <= 20; x++) @{
  1032.          if (x == 5)
  1033.              continue
  1034.          printf ("%d ", x)
  1035.      @}
  1036.      print ""
  1037. @}'
  1038. @end example
  1039.  
  1040. @noindent
  1041. This program prints all the numbers from 0 to 20, except for 5, for
  1042. which the @code{printf} is skipped.  Since the increment @code{x++}
  1043. is not skipped, @code{x} does not remain stuck at 5.  Contrast the
  1044. @code{for} loop above with the @code{while} loop:
  1045.  
  1046. @example
  1047. awk 'BEGIN @{
  1048.      x = 0
  1049.      while (x <= 20) @{
  1050.          if (x == 5)
  1051.              continue
  1052.          printf ("%d ", x)
  1053.          x++
  1054.      @}
  1055.      print ""
  1056. @}'
  1057. @end example
  1058.  
  1059. @noindent
  1060. This program loops forever once @code{x} gets to 5.
  1061.  
  1062. @node Next Statement, Exit Statement, Continue Statement, Statements
  1063. @section The @code{next} Statement
  1064. @cindex @code{next} statement
  1065.  
  1066. The @code{next} statement forces @code{awk} to immediately stop processing
  1067. the current record and go on to the next record.  This means that no
  1068. further rules are executed for the current record.  The rest of the
  1069. current rule's action is not executed either.
  1070.  
  1071. Contrast this with the effect of the @code{getline} function
  1072. (@pxref{Getline}).  That too causes @code{awk} to read the next record
  1073. immediately, but it does not alter the flow of control in any way.  So
  1074. the rest of the current action executes with a new input record.
  1075.  
  1076. At the grossest level, @code{awk} program execution is a loop that reads
  1077. an input record and then tests each rule's pattern against it.  If you
  1078. think of this loop as a @code{for} statement whose body contains the
  1079. rules, then the @code{next} statement is analogous to a @code{continue}
  1080. statement: it skips to the end of the body of this implicit loop, and
  1081. executes the increment (which reads another record).
  1082.  
  1083. For example, if your @code{awk} program works only on records with four
  1084. fields, and you don't want it to fail when given bad input, you might
  1085. use this rule near the beginning of the program:
  1086.  
  1087. @example
  1088. NF != 4 @{
  1089.   printf("line %d skipped: doesn't have 4 fields", FNR) > "/dev/stderr"
  1090.   next
  1091. @}
  1092. @end example
  1093.  
  1094. @noindent
  1095. so that the following rules will not see the bad record.  The error
  1096. message is redirected to the standard error output stream, as error
  1097. messages should be.  @xref{Special Files}.
  1098.  
  1099. The @code{next} statement is not allowed in a @code{BEGIN} or @code{END}
  1100. rule.
  1101.  
  1102. @node Exit Statement, , Next Statement, Statements
  1103. @section The @code{exit} Statement
  1104.  
  1105. @cindex @code{exit} statement
  1106. The @code{exit} statement causes @code{awk} to immediately stop
  1107. executing the current rule and to stop processing input; any remaining input
  1108. is ignored.@refill
  1109.  
  1110. If an @code{exit} statement is executed from a @code{BEGIN} rule the
  1111. program stops processing everything immediately.  No input records are
  1112. read.  However, if an @code{END} rule is present, it is executed
  1113. (@pxref{BEGIN/END}).
  1114.  
  1115. If @code{exit} is used as part of an @code{END} rule, it causes
  1116. the program to stop immediately.
  1117.  
  1118. An @code{exit} statement that is part an ordinary rule (that is, not part
  1119. of a @code{BEGIN} or @code{END} rule) stops the execution of any further
  1120. automatic rules, but the @code{END} rule is executed if there is one.
  1121. If you don't want the @code{END} rule to do its job in this case, you
  1122. can set a variable to nonzero before the @code{exit} statement, and check
  1123. that variable in the @code{END} rule.
  1124.  
  1125. If an argument is supplied to @code{exit}, its value is used as the exit
  1126. status code for the @code{awk} process.  If no argument is supplied,
  1127. @code{exit} returns status zero (success).@refill
  1128.  
  1129. For example, let's say you've discovered an error condition you really
  1130. don't know how to handle.  Conventionally, programs report this by
  1131. exiting with a nonzero status.  Your @code{awk} program can do this
  1132. using an @code{exit} statement with a nonzero argument.  Here's an
  1133. example of this:@refill
  1134.  
  1135. @example
  1136. BEGIN @{
  1137.        if (("date" | getline date_now) < 0) @{
  1138.          print "Can't get system date" > "/dev/stderr"
  1139.          exit 4
  1140.        @}
  1141. @}
  1142. @end example
  1143.  
  1144. @node Arrays, Built-in, Statements, Top
  1145. @chapter Arrays in @code{awk}
  1146.  
  1147. An @dfn{array} is a table of various values, called @dfn{elements}.  The
  1148. elements of an array are distinguished by their @dfn{indices}.  Indices
  1149. may be either numbers or strings.  Each array has a name, which looks
  1150. like a variable name, but must not be in use as a variable name in the
  1151. same @code{awk} program.
  1152.  
  1153. @menu
  1154. * Intro: Array Intro.      Basic facts about arrays in @code{awk}.
  1155. * Reference to Elements::  How to examine one element of an array.
  1156. * Assigning Elements::     How to change an element of an array.
  1157. * Example: Array Example.  Sample program explained.
  1158.  
  1159. * Scanning an Array::      A variation of the @code{for} statement.  It loops
  1160.                            through the indices of an array's existing elements.
  1161.  
  1162. * Delete::                 The @code{delete} statement removes an element from an array.
  1163.  
  1164. * Multi-dimensional::      Emulating multi-dimensional arrays in @code{awk}.
  1165. * Multi-scanning::         Scanning multi-dimensional arrays.
  1166. @end menu
  1167.  
  1168. @node Array Intro, Reference to Elements, Arrays, Arrays
  1169. @section Introduction to Arrays
  1170.  
  1171. @cindex arrays
  1172. The @code{awk} language has one-dimensional @dfn{arrays} for storing groups
  1173. of related strings or numbers.
  1174.  
  1175. Every @code{awk} array must have a name.  Array names have the same
  1176. syntax as variable names; any valid variable name would also be a valid
  1177. array name.  But you cannot use one name in both ways (as an array and
  1178. as a variable) in one @code{awk} program.
  1179.  
  1180. Arrays in @code{awk} superficially resemble arrays in other programming
  1181. languages; but there are fundamental differences.  In @code{awk}, you
  1182. don't need to specify the size of an array before you start to use it.
  1183. What's more, in @code{awk} any number or even a string may be used as an
  1184. array index.
  1185.  
  1186. In most other languages, you have to @dfn{declare} an array and specify
  1187. how many elements or components it has.  In such languages, the
  1188. declaration causes a contiguous block of memory to be allocated for that
  1189. many elements.  An index in the array must be a positive integer; for
  1190. example, the index 0 specifies the first element in the array, which is
  1191. actually stored at the beginning of the block of memory.  Index 1
  1192. specifies the second element, which is stored in memory right after the
  1193. first element, and so on.  It is impossible to add more elements to the
  1194. array, because it has room for only as many elements as you declared.
  1195.  
  1196. A contiguous array of four elements might look like this, conceptually,
  1197. if the element values are 8, @code{"foo"}, @code{""} and 30:@refill
  1198.  
  1199. @example
  1200. +---------+---------+--------+---------+
  1201. |    8    |  "foo"  |   ""   |    30   |    @r{value}
  1202. +---------+---------+--------+---------+
  1203.      0         1         2         3        @r{index}
  1204. @end example
  1205.  
  1206. @noindent
  1207. Only the values are stored; the indices are implicit from the order of
  1208. the values.  8 is the value at index 0, because 8 appears in the
  1209. position with 0 elements before it.
  1210.  
  1211. @cindex arrays, definition of
  1212. @cindex associative arrays
  1213. Arrays in @code{awk} are different: they are @dfn{associative}.  This means
  1214. that each array is a collection of pairs: an index, and its corresponding
  1215. array element value:
  1216.  
  1217. @example
  1218. @r{Element} 4     @r{Value} 30
  1219. @r{Element} 2     @r{Value} "foo"
  1220. @r{Element} 1     @r{Value} 8
  1221. @r{Element} 3     @r{Value} ""
  1222. @end example
  1223.  
  1224. @noindent
  1225. We have shown the pairs in jumbled order because their order doesn't
  1226. mean anything.
  1227.  
  1228. One advantage of an associative array is that new pairs can be added
  1229. at any time.  For example, suppose we add to that array a tenth element
  1230. whose value is @w{@code{"number ten"}}.  The result is this:
  1231.  
  1232. @example
  1233. @r{Element} 10    @r{Value} "number ten"
  1234. @r{Element} 4     @r{Value} 30
  1235. @r{Element} 2     @r{Value} "foo"
  1236. @r{Element} 1     @r{Value} 8
  1237. @r{Element} 3     @r{Value} ""
  1238. @end example
  1239.  
  1240. @noindent
  1241. Now the array is @dfn{sparse} (i.e., some indices are missing): it has
  1242. elements 4 and 10, but doesn't have elements 5, 6, 7, 8, or 9.@refill
  1243.  
  1244. Another consequence of associative arrays is that the indices don't
  1245. have to be positive integers.  Any number, or even a string, can be
  1246. an index.  For example, here is an array which translates words from
  1247. English into French:
  1248.  
  1249. @example
  1250. @r{Element} "dog" @r{Value} "chien"
  1251. @r{Element} "cat" @r{Value} "chat"
  1252. @r{Element} "one" @r{Value} "un"
  1253. @r{Element} 1     @r{Value} "un"
  1254. @end example
  1255.  
  1256. @noindent
  1257. Here we decided to translate the number 1 in both spelled-out and
  1258. numeric form---thus illustrating that a single array can have both
  1259. numbers and strings as indices.
  1260.  
  1261. When @code{awk} creates an array for you, e.g., with the @code{split}
  1262. built-in function (@pxref{String Functions}), that array's indices
  1263. are consecutive integers starting at 1.
  1264.  
  1265. @node Reference to Elements, Assigning Elements, Array Intro, Arrays
  1266. @section Referring to an Array Element
  1267. @cindex array reference
  1268. @cindex element of array
  1269. @cindex reference to array
  1270.  
  1271. The principal way of using an array is to refer to one of its elements.
  1272. An array reference is an expression which looks like this:
  1273.  
  1274. @example
  1275. @var{array}[@var{index}]
  1276. @end example
  1277.  
  1278. @noindent
  1279. Here @var{array} is the name of an array.  The expression @var{index} is
  1280. the index of the element of the array that you want.
  1281.  
  1282. The value of the array reference is the current value of that array
  1283. element.  For example, @code{foo[4.3]} is an expression for the element
  1284. of array @code{foo} at index 4.3.
  1285.  
  1286. If you refer to an array element that has no recorded value, the value
  1287. of the reference is @code{""}, the null string.  This includes elements
  1288. to which you have not assigned any value, and elements that have been
  1289. deleted (@pxref{Delete}).  Such a reference automatically creates that
  1290. array element, with the null string as its value.  (In some cases,
  1291. this is unfortunate, because it might waste memory inside @code{awk}).
  1292.  
  1293. @cindex arrays, determining presence of elements
  1294. You can find out if an element exists in an array at a certain index with
  1295. the expression:
  1296.  
  1297. @example
  1298. @var{index} in @var{array}
  1299. @end example
  1300.  
  1301. @noindent
  1302. This expression tests whether or not the particular index exists,
  1303. without the side effect of creating that element if it is not present.
  1304. The expression has the value 1 (true) if @code{@var{array}[@var{index}]}
  1305. exists, and 0 (false) if it does not exist.@refill
  1306.  
  1307. For example, to test whether the array @code{frequencies} contains the
  1308. index @code{"2"}, you could write this statement:@refill
  1309.  
  1310. @example
  1311. if ("2" in frequencies) print "Subscript \"2\" is present."
  1312. @end example
  1313.  
  1314. Note that this is @emph{not} a test of whether or not the array
  1315. @code{frequencies} contains an element whose @emph{value} is @code{"2"}.
  1316. (There is no way to do that except to scan all the elements.)  Also, this
  1317. @emph{does not} create @code{frequencies["2"]}, while the following
  1318. (incorrect) alternative would do so:@refill
  1319.  
  1320. @example
  1321. if (frequencies["2"] != "") print "Subscript \"2\" is present."
  1322. @end example
  1323.  
  1324. @node Assigning Elements, Array Example, Reference to Elements, Arrays
  1325. @section Assigning Array Elements
  1326. @cindex array assignment
  1327. @cindex element assignment
  1328.  
  1329. Array elements are lvalues: they can be assigned values just like
  1330. @code{awk} variables:
  1331.  
  1332. @example
  1333. @var{array}[@var{subscript}] = @var{value}
  1334. @end example
  1335.  
  1336. @noindent
  1337. Here @var{array} is the name of your array.  The expression
  1338. @var{subscript} is the index of the element of the array that you want
  1339. to assign a value.  The expression @var{value} is the value you are
  1340. assigning to that element of the array.@refill
  1341.  
  1342. @node Array Example, Scanning an Array, Assigning Elements, Arrays
  1343. @section Basic Example of an Array
  1344.  
  1345. The following program takes a list of lines, each beginning with a line
  1346. number, and prints them out in order of line number.  The line numbers are
  1347. not in order, however, when they are first read:  they are scrambled.  This
  1348. program sorts the lines by making an array using the line numbers as
  1349. subscripts.  It then prints out the lines in sorted order of their numbers.
  1350. It is a very simple program, and gets confused if it encounters repeated
  1351. numbers, gaps, or lines that don't begin with a number.@refill
  1352.  
  1353. @example
  1354. @{
  1355.   if ($1 > max)
  1356.     max = $1
  1357.   arr[$1] = $0
  1358. @}
  1359.  
  1360. END @{
  1361.   for (x = 1; x <= max; x++)
  1362.     print arr[x]
  1363. @}
  1364. @end example
  1365.  
  1366. @ignore
  1367. The first rule just initializes the variable @code{max}.  (This is not
  1368. strictly necessary, since an uninitialized variable has the null string
  1369. as its value, and the null string is effectively zero when used in
  1370. a context where a number is required.)
  1371. @end ignore
  1372.  
  1373. The first rule keeps track of the largest line number seen so far;
  1374. it also stores each line into the array @code{arr}, at an index that
  1375. is the line's number.
  1376.  
  1377. The second rule runs after all the input has been read, to print out
  1378. all the lines.
  1379.  
  1380. When this program is run with the following input:
  1381.  
  1382. @example
  1383. 5  I am the Five man
  1384. 2  Who are you?  The new number two!
  1385. 4  . . . And four on the floor
  1386. 1  Who is number one?
  1387. 3  I three you.
  1388. @end example
  1389.  
  1390. @noindent
  1391. its output is this:
  1392.  
  1393. @example
  1394. 1  Who is number one?
  1395. 2  Who are you?  The new number two!
  1396. 3  I three you.
  1397. 4  . . . And four on the floor
  1398. 5  I am the Five man
  1399. @end example
  1400.  
  1401.