home *** CD-ROM | disk | FTP | other *** search
/ Garbo / Garbo.cdr / pc / unix / gawk_doc.zoo / gawk-info-4 < prev    next >
Encoding:
Text File  |  1989-04-13  |  50.3 KB  |  1,400 lines

  1. Info file gawk-info, produced by Makeinfo, -*- Text -*- from input
  2. file gawk.texinfo.
  3.  
  4. This file documents `awk', a program that you can use to select
  5. particular records in a file and perform operations upon them.
  6.  
  7. Copyright (C) 1989 Free Software Foundation, Inc.
  8.  
  9. Permission is granted to make and distribute verbatim copies of this
  10. manual provided the copyright notice and this permission notice are
  11. preserved on all copies.
  12.  
  13. Permission is granted to copy and distribute modified versions of
  14. this manual under the conditions for verbatim copying, provided that
  15. the entire resulting derived work is distributed under the terms of a
  16. permission notice identical to this one.
  17.  
  18. Permission is granted to copy and distribute translations of this
  19. manual into another language, under the above conditions for modified
  20. versions, except that this permission notice may be stated in a
  21. translation approved by the Foundation.
  22.  
  23.  
  24. 
  25. File: gawk-info,  Node: For,  Next: Break,  Prev: Do,  Up: Statements
  26.  
  27. The `for' Statement
  28. ===================
  29.  
  30. The `for' statement makes it more convenient to count iterations of a
  31. loop.  The general form of the `for' statement looks like this:
  32.  
  33.      for (INITIALIZATION; CONDITION; INCREMENT)
  34.        BODY
  35.  
  36. This statement starts by executing INITIALIZATION.  Then, as long as
  37. CONDITION is true, it repeatedly executes BODY and then INCREMENT. 
  38. Typically INITIALIZATION sets a variable to either zero or one,
  39. INCREMENT adds 1 to it, and CONDITION compares it against the desired
  40. number of iterations.
  41.  
  42. Here is an example of a `for' statement:
  43.  
  44.      awk '{ for (i = 1; i <= 3; i++)
  45.                print $i
  46.      }'
  47.  
  48. This prints the first three fields of each input record, one field
  49. per line.
  50.  
  51. In the `for' statement, BODY stands for any statement, but
  52. INITIALIZATION, CONDITION and INCREMENT are just expressions.  You
  53. cannot set more than one variable in the INITIALIZATION part unless
  54. you use a multiple assignment statement such as `x = y = 0', which is
  55. possible only if all the initial values are equal.  (But you can
  56. initialize additional variables by writing their assignments as
  57. separate statements preceding the `for' loop.)
  58.  
  59. The same is true of the INCREMENT part; to increment additional
  60. variables, you must write separate statements at the end of the loop.
  61. The C compound expression, using C's comma operator, would be useful
  62. in this context, but it is not supported in `awk'.
  63.  
  64. Most often, INCREMENT is an increment expression, as in the example
  65. above.  But this is not required; it can be any expression whatever. 
  66. For example, this statement prints odd numbers from 1 to 100:
  67.  
  68.      # print odd numbers from 1 to 100
  69.      for (i = 1; i <= 100; i += 2)
  70.        print i
  71.  
  72. Any of the three expressions following `for' may be omitted if you
  73. don't want it to do anything.  Thus, `for (;x > 0;)' is equivalent to
  74. `while (x > 0)'.  If the CONDITION part is empty, it is treated as
  75. TRUE, effectively yielding an infinite loop.
  76.  
  77. In most cases, a `for' loop is an abbreviation for a `while' loop, as
  78. shown here:
  79.  
  80.      INITIALIZATION
  81.      while (CONDITION) {
  82.        BODY
  83.        INCREMENT
  84.      }
  85.  
  86. (The only exception is when the `continue' statement (*note
  87. Continue::.) is used inside the loop; changing a `for' statement to a
  88. `while' statement in this way can change the effect of the `continue'
  89. statement inside the loop.)
  90.  
  91. The `awk' language has a `for' statement in addition to a `while'
  92. statement because often a `for' loop is both less work to type and
  93. more natural to think of.  Counting the number of iterations is very
  94. common in loops.  It can be easier to think of this counting as part
  95. of looping rather than as something to do inside the loop.
  96.  
  97. The next section has more complicated examples of `for' loops.
  98.  
  99. There is an alternate version of the `for' loop, for iterating over
  100. all the indices of an array:
  101.  
  102.      for (i in array)
  103.          PROCESS array[i]
  104.  
  105. *Note Arrays::, for more information on this version of the `for' loop.
  106.  
  107.  
  108. 
  109. File: gawk-info,  Node: Break,  Next: Continue,  Prev: For,  Up: Statements
  110.  
  111. The `break' Statement
  112. =====================
  113.  
  114. The `break' statement jumps out of the innermost `for', `while', or
  115. `do'--`while' loop that encloses it.  The following example finds the
  116. smallest divisor of any number, and also identifies prime numbers:
  117.  
  118.      awk '# find smallest divisor of num
  119.           { num = $1
  120.             for (div = 2; div*div <= num; div++)
  121.               if (num % div == 0)
  122.                 break
  123.             if (num % div == 0)
  124.               printf "Smallest divisor of %d is %d\n", num, div
  125.             else
  126.               printf "%d is prime\n", num  }'
  127.  
  128. When the remainder is zero in the first `if' statement, `awk'
  129. immediately "breaks" out of the containing `for' loop.  This means
  130. that `awk' proceeds immediately to the statement following the loop
  131. and continues processing.  (This is very different from the `exit'
  132. statement (*note Exit::.) which stops the entire `awk' program.)
  133.  
  134. Here is another program equivalent to the previous one.  It
  135. illustrates how the CONDITION of a `for' or `while' could just as
  136. well be replaced with a `break' inside an `if':
  137.  
  138.      awk '# find smallest divisor of num
  139.           { num = $1
  140.             for (div = 2; ; div++) {
  141.               if (num % div == 0) {
  142.                 printf "Smallest divisor of %d is %d\n", num, div
  143.                 break
  144.               }
  145.               if (div*div > num) {
  146.                 printf "%d is prime\n", num
  147.                 break
  148.               }
  149.             }
  150.      }'
  151.  
  152.  
  153. 
  154. File: gawk-info,  Node: Continue,  Next: Next,  Prev: Break,  Up: Statements
  155.  
  156. The `continue' Statement
  157. ========================
  158.  
  159. The `continue' statement, like `break', is used only inside `for',
  160. `while', and `do'--`while' loops.  It skips over the rest of the loop
  161. body, causing the next cycle around the loop to begin immediately. 
  162. Contrast this with `break', which jumps out of the loop altogether. 
  163. Here is an example:
  164.  
  165.      # print names that don't contain the string "ignore"
  166.      
  167.      # first, save the text of each line
  168.      { names[NR] = $0 }
  169.      
  170.      # print what we're interested in
  171.      END {
  172.         for (x in names) {
  173.             if (names[x] ~ /ignore/)
  174.                 continue
  175.             print names[x]
  176.         }
  177.      }
  178.  
  179. If any of the input records contain the string `ignore', this example
  180. skips the print statement and continues back to the first statement
  181. in the loop.
  182.  
  183. This isn't a practical example of `continue', since it would be just
  184. as easy to write the loop like this:
  185.  
  186.      for (x in names)
  187.        if (x !~ /ignore/)
  188.          print x
  189.  
  190. The `continue' statement causes `awk' to skip the rest of what is
  191. inside a `for' loop, but it resumes execution with the increment part
  192. of the `for' loop.  The following program illustrates this fact:
  193.  
  194.      awk 'BEGIN {
  195.           for (x = 0; x <= 20; x++) {
  196.               if (x == 5)
  197.                   continue
  198.               printf ("%d ", x)
  199.           }
  200.           print ""
  201.      }'
  202.  
  203. This program prints all the numbers from 0 to 20, except for 5, for
  204. which the `printf' is skipped.  Since the increment `x++' is not
  205. skipped, `x' does not remain stuck at 5.
  206.  
  207.  
  208. 
  209. File: gawk-info,  Node: Next,  Next: Exit,  Prev: Continue,  Up: Statements
  210.  
  211. The `next' Statement
  212. ====================
  213.  
  214. The `next' statement forces `awk' to immediately stop processing the
  215. current record and go on to the next record.  This means that no
  216. further rules are executed for the current record.  The rest of the
  217. current rule's action is not executed either.
  218.  
  219. Contrast this with the effect of the `getline' function (*note
  220. Getline::.).  That too causes `awk' to read the next record
  221. immediately, but it does not alter the flow of control in any way. 
  222. So the rest of the current action executes with a new input record.
  223.  
  224. At the grossest level, `awk' program execution is a loop that reads
  225. an input record and then tests each rule pattern against it.  If you
  226. think of this loop as a `for' statement whose body contains the
  227. rules, then the `next' statement is analogous to a `continue'
  228. statement: it skips to the end of the body of the loop, and executes
  229. the increment (which reads another record).
  230.  
  231. For example, if your `awk' program works only on records with four
  232. fields, and you don't want it to fail when given bad input, you might
  233. use the following rule near the beginning of the program:
  234.  
  235.      NF != 4 {
  236.        printf ("line %d skipped: doesn't have 4 fields", FNR) > "/dev/tty"
  237.        next
  238.      }
  239.  
  240. so that the following rules will not see the bad record.  The error
  241. message is redirected to `/dev/tty' (the terminal), so that it won't
  242. get lost amid the rest of the program's regular output.
  243.  
  244.  
  245. 
  246. File: gawk-info,  Node: Exit,  Prev: Next,  Up: Statements
  247.  
  248. The `exit' Statement
  249. ====================
  250.  
  251. The `exit' statement causes `awk' to immediately stop executing the
  252. current rule and to stop processing input; any remaining input is
  253. ignored.
  254.  
  255. If an `exit' statement is executed from a `BEGIN' rule the program
  256. stops processing everything immediately.  No input records will be
  257. read.  However, if an `END' rule is present, it will be executed
  258. (*note BEGIN/END::.).
  259.  
  260. If `exit' is used as part of an `END' rule, it causes the program to
  261. stop immediately.
  262.  
  263. An `exit' statement that is part an ordinary rule (that is, not part
  264. of a `BEGIN' or `END' rule) stops the execution of any further
  265. automatic rules, but the `END' rule is executed if there is one.  If
  266. you don't want the `END' rule to do its job in this case, you can set
  267. a variable to nonzero before the `exit' statement, and check that
  268. variable in the `END' rule.
  269.  
  270. If an argument is supplied to `exit', its value is used as the exit
  271. status code for the `awk' process.  If no argument is supplied,
  272. `exit' returns status zero (success).
  273.  
  274. For example, let's say you've discovered an error condition you
  275. really don't know how to handle.  Conventionally, programs report
  276. this by exiting with a nonzero status.  Your `awk' program can do
  277. this using an `exit' statement with a nonzero argument.  Here's an
  278. example of this:
  279.  
  280.      BEGIN {
  281.             if (("date" | getline date_now) < 0) {
  282.               print "Can't get system date"
  283.               exit 4
  284.             }
  285.      }
  286.  
  287.  
  288. 
  289. File: gawk-info,  Node: Arrays,  Next: Built-in,  Prev: Statements,  Up: Top
  290.  
  291. Actions: Using Arrays in `awk'
  292. ******************************
  293.  
  294. An "array" is a table of various values, called "elements".  The
  295. elements of an array are distinguished by their "indices".  Names of
  296. arrays in `awk' are strings of alphanumeric characters and
  297. underscores, just like regular variables.
  298.  
  299. You cannot use the same identifier as both a variable and as an array
  300. name in one `awk' program.
  301.  
  302. * Menu:
  303.  
  304. * Intro: Array Intro.      Basic facts abou arrays in `awk'.
  305. * Reference to Elements::  How to examine one element of an array.
  306. * Assigning Elements::     How to change an element of an array.
  307. * Example: Array Example.  Sample program explained.
  308.  
  309. * Scanning an Array::      A variation of the `for' statement.  It loops
  310.                            through the indices of an array's existing elements.
  311.  
  312. * Delete::                 The `delete' statement removes an element from an array.
  313.  
  314. * Multi-dimensional::      Emulating multi--dimensional arrays in `awk'.
  315. * Multi-scanning::         Scanning multi--dimensional arrays.
  316.  
  317.  
  318. 
  319. File: gawk-info,  Node: Array Intro,  Next: Reference to Elements,  Up: Arrays
  320.  
  321. Introduction to Arrays
  322. ======================
  323.  
  324. The `awk' language has one--dimensional "arrays" for storing groups
  325. of related strings or numbers.  Each array must have a name; valid
  326. array names are the same as valid variable names, and they do
  327. conflict with variable names: you can't have both an array and a
  328. variable with the same name at any point in an `awk' program.
  329.  
  330. Arrays in `awk' superficially resemble arrays in other programming
  331. languages; but there are fundamental differences.  In `awk', you
  332. don't need to declare the size of an array before you start to use it.
  333. What's more, in `awk' any number or even a string may be used as an
  334. array index.
  335.  
  336. In most other languages, you have to "declare" an array and specify
  337. how many elements or components it has.  In such languages, the
  338. declaration causes a contiguous block of memory to be allocated for
  339. that many elements.  An index in the array must be a positive
  340. integer; for example, the index 0 specifies the first element in the
  341. array, which is actually stored at the beginning of the block of
  342. memory.  Index 1 specifies the second element, which is stored in
  343. memory right after the first element, and so on.  It is impossible to
  344. add more elements to the array, because it has room for only as many
  345. elements as you declared.  (Some languages have arrays whose first
  346. index is 1, others require that you specify both the first and last
  347. index when you declare the array.  In such a language, an array could
  348. be indexed, for example, from -3 to 17.)  A contiguous array of four
  349. elements might look like this, conceptually, if the element values
  350. are 8, `"foo"', `""' and 30:
  351.  
  352.      +--------+--------+-------+--------+
  353.      |    8    |  "foo"  |   ""   |    30   |    value
  354.      +--------+--------+-------+--------+
  355.           0         1         2         3        index
  356.  
  357. Only the values are stored; the indices are implicit from the order
  358. of the values.  8 is the value at index 0, because 8 appears in the
  359. position with 0 elements before it.
  360.  
  361. Arrays in `awk' are different: they are "associative".  This means
  362. that each array is a collection of pairs: an index, and its
  363. corresponding array element value:
  364.  
  365.      Element 4     Value 30
  366.      Element 2     Value "foo"
  367.      Element 1     Value 8
  368.      Element 3     Value ""
  369.  
  370. We have shown the pairs in jumbled order because their order doesn't
  371. mean anything.
  372.  
  373. One advantage of an associative array is that new pairs can be added
  374. at any time.  For example, suppose we add to that array a tenth
  375. element whose value is `"number ten"'.  The result is this:
  376.  
  377.      Element 10    Value "number ten"
  378.      Element 4     Value 30
  379.      Element 2     Value "foo"
  380.      Element 1     Value 8
  381.      Element 3     Value ""
  382.  
  383. Now the array is "sparse" (i.e. some indices are missing): it has
  384. elements number 4 and 10, but doesn't have an element 5, 6, 7, 8, or 9.
  385.  
  386. Another consequence of associative arrays is that the indices don't
  387. have to be positive integers.  Any number, or even a string, can be
  388. an index.  For example, here is an array which translates words from
  389. English into French:
  390.  
  391.      Element "dog" Value "chien"
  392.      Element "cat" Value "chat"
  393.      Element "one" Value "un"
  394.      Element 1     Value "un"
  395.  
  396. Here we decided to translate the number 1 in both spelled--out and
  397. numeral form--thus illustrating that a single array can have both
  398. numbers and strings as indices.
  399.  
  400. When `awk' creates an array for you, e.g. with the `split' built--in
  401. function (*note String Functions::.), that array's indices start at
  402. the number one.
  403.  
  404.  
  405. 
  406. File: gawk-info,  Node: Reference to Elements,  Next: Assigning Elements,  Prev: Array Intro,  Up: Arrays
  407.  
  408. Referring to an Array Element
  409. =============================
  410.  
  411. The principal way of using an array is to refer to one of its elements.
  412. An array reference is an expression which looks like this:
  413.  
  414.      ARRAY[INDEX]
  415.  
  416. Here ARRAY is the name of an array.  The expression INDEX is the
  417. index of the element of the array that you want.  The value of the
  418. array reference is the current value of that array element.
  419.  
  420. For example, `foo[4.3]' is an expression for the element of array
  421. `foo' at index 4.3.
  422.  
  423. If you refer to an array element that has no recorded value, the
  424. value of the reference is `""', the null string.  This includes
  425. elements to which you have not assigned any value, and elements that
  426. have been deleted (*note Delete::.).  Such a reference automatically
  427. creates that array element, with the null string as its value.  (In
  428. some cases, this is unfortunate, because it might waste memory inside
  429. `awk').
  430.  
  431. You can find out if an element exists in an array at a certain index
  432. with the expression:
  433.  
  434.      INDEX in ARRAY
  435.  
  436. This expression tests whether or not the particular index exists,
  437. without the side effect of creating that element if it is not present.
  438. The expression has the value 1 (true) if `ARRAY[SUBSCRIPT]' exists,
  439. and 0 (false) if it does not exist.
  440.  
  441. For example, to find out whether the array `frequencies' contains the
  442. subscript `"2"', you would ask:
  443.  
  444.      if ("2" in frequencies) print "Subscript \"2\" is present."
  445.  
  446. Note that this is *not* a test of whether or not the array
  447. `frequencies' contains an element whose *value* is `"2"'.  (There is
  448. no way to that except to scan all the elements.)  Also, this *does
  449. not* create `frequencies["2"]', while the following (incorrect)
  450. alternative would:
  451.  
  452.      if (frequencies["2"] != "") print "Subscript \"2\" is present."
  453.  
  454.  
  455. 
  456. File: gawk-info,  Node: Assigning Elements,  Next: Array Example,  Prev: Reference to Elements,  Up: Arrays
  457.  
  458. Assigning Array Elements
  459. ========================
  460.  
  461. Array elements are lvalues: they can be assigned values just like
  462. `awk' variables:
  463.  
  464.      ARRAY[SUBSCRIPT] = VALUE
  465.  
  466. Here ARRAY is the name of your array.  The expression SUBSCRIPT is
  467. the index of the element of the array that you want to assign a
  468. value.  The expression VALUE is the value you are assigning to that
  469. element of the array.
  470.  
  471.  
  472. 
  473. File: gawk-info,  Node: Array Example,  Next: Scanning an Array,  Prev: Assigning Elements,  Up: Arrays
  474.  
  475. Basic Example of an Array
  476. =========================
  477.  
  478. The following program takes a list of lines, each beginning with a
  479. line number, and prints them out in order of line number.  The line
  480. numbers are not in order, however, when they are first read:  they
  481. are scrambled.  This program sorts the lines by making an array using
  482. the line numbers as subscripts.  It then prints out the lines in
  483. sorted order of their numbers.  It is a very simple program, and will
  484. get confused if it encounters repeated numbers, gaps, or lines that
  485. don't begin with a number.
  486.  
  487.      BEGIN {
  488.        max=0
  489.      }
  490.      
  491.      {
  492.        if ($1 > max)
  493.          max = $1
  494.        arr[$1] = $0
  495.      }
  496.      
  497.      END {
  498.        for (x = 1; x <= max; x++)
  499.          print arr[x]
  500.      }
  501.  
  502. The first rule just initializes the variable `max'.  (This is not
  503. strictly necessary, since an uninitialized variable has the null
  504. string as its value, and the null string is effectively zero when
  505. used in a context where a number is required.)
  506.  
  507. The second rule keeps track of the largest line number seen so far;
  508. it also stores each line into the array `arr', at an index that is
  509. the line's number.
  510.  
  511. The third rule runs after all the input has been read, to print out
  512. all the lines.
  513.  
  514. When this program is run with the following input:
  515.  
  516.      5  I am the Five man
  517.      2  Who are you?  The new number two!
  518.      4  . . . And four on the floor
  519.      1  Who is number one?
  520.      3  I three you.
  521.  
  522.  its output is this:
  523.  
  524.      1  Who is number one?
  525.      2  Who are you?  The new number two!
  526.      3  I three you.
  527.      4  . . . And four on the floor
  528.      5  I am the Five man
  529.  
  530.  
  531. 
  532. File: gawk-info,  Node: Scanning an Array,  Next: Delete,  Prev: Array Example,  Up: Arrays
  533.  
  534. Scanning All Elements of an Array
  535. =================================
  536.  
  537. In programs that use arrays, often you need a loop that will execute
  538. once for each element of an array.  In other languages, where arrays
  539. are contiguous and indices are limited to positive integers, this is
  540. easy: the largest index is one less than the length of the array, and
  541. you can find all the valid indices by counting from zero up to that
  542. value.  This technique won't do the job in `awk', since any number or
  543. string may be an array index.  So `awk' has a special kind of `for'
  544. statement for scanning an array:
  545.  
  546.      for (VAR in ARRAY)
  547.        BODY
  548.  
  549. This loop executes BODY once for each different value that your
  550. program has previously used as an index in ARRAY, with the variable
  551. VAR set to that index.
  552.  
  553. Here is a program that uses this form of the `for' statement.  The
  554. first rule scans the input records and notes which words appear (at
  555. least once) in the input, by storing a 1 into the array `used' with
  556. the word as index.  The second rule scans the elements of `used' to
  557. find all the distinct words that appear in the input.  It prints each
  558. word that is more than 10 characters long, and also prints the number
  559. of such words.  *Note Built-in::, for more information on the
  560. built--in function `length'.
  561.  
  562.      # Record a 1 for each word that is used at least once.
  563.      {
  564.        for (i = 0; i < NF; i++)
  565.          used[$i] = 1
  566.      }
  567.      
  568.      # Find number of distinct words more than 10 characters long.
  569.      END {
  570.        num_long_words = 0
  571.        for (x in used)
  572.          if (length(x) > 10) {
  573.            ++num_long_words
  574.            print x
  575.        }
  576.        print num_long_words, "words longer than 10 characters"
  577.      }
  578.  
  579. *Note Sample Program::, for a more detailed example of this type.
  580.  
  581. The order in which elements of the array are accessed by this
  582. statement is determined by the internal arrangement of the array
  583. elements within `awk' and cannot be controlled or changed.  This can
  584. lead to problems if new elements are added to ARRAY by statements in
  585. BODY; you cannot predict whether or not the `for' loop will reach
  586. them.  Similarly, changing VAR inside the loop can produce strange
  587. results.  It is best to avoid such things.
  588.  
  589.  
  590. 
  591. File: gawk-info,  Node: Delete,  Next: Multi-dimensional,  Prev: Scanning an Array,  Up: Arrays
  592.  
  593. The `delete' Statement
  594. ======================
  595.  
  596. You can remove an individual element of an array using the `delete'
  597. statement:
  598.  
  599.      delete ARRAY[INDEX]
  600.  
  601. When an array element is deleted, it is as if you had never referred
  602. to it and had never given it any value.  Any value the element
  603. formerly had can no longer be obtained.
  604.  
  605. Here is an example of deleting elements in an array:
  606.  
  607.      awk '{ for (i in frequencies)
  608.                  delete frequencies[i]
  609.      }'
  610.  
  611. This example removes all the elements from the array `frequencies'.
  612.  
  613. If you delete an element, the `for' statement to scan the array will
  614. not report that element, and the `in' operator to check for the
  615. presence of that element will return 0:
  616.  
  617.      delete foo[4]
  618.      if (4 in foo)
  619.        print "This will never be printed"
  620.  
  621.  
  622. 
  623. File: gawk-info,  Node: Multi-dimensional,  Next: Multi-scanning,  Prev: Delete,  Up: Arrays
  624.  
  625. Multi--dimensional arrays
  626. =========================
  627.  
  628. A multi--dimensional array is an array in which an element is
  629. identified by a sequence of indices, not a single index.  For
  630. example, a two--dimensional array requires two indices.  The usual
  631. way (in most languages, including `awk') to refer to an element of a
  632. two--dimensional array named `grid' is with `grid[x,y]'.
  633.  
  634. Multi--dimensional arrays are supported in `awk' through
  635. concatenation of indices into one string.  What happens is that `awk'
  636. converts the indices into strings (*note Conversion::.) and
  637. concatenates them together, with a separator between them.  This
  638. creates a single string that describes the values of the separate
  639. indices.  The combined string is used as a single index into an
  640. ordinary, one--dimensional array.  The separator used is the value of
  641. the special variable `SUBSEP'.
  642.  
  643. For example, suppose the value of `SUBSEP' is `","' and the
  644. expression `foo[5,12]="value"' is executed.  The numbers 5 and 12
  645. will be concatenated with a comma between them, yielding `"5,12"';
  646. thus, the array element `foo["5,12"]' will be set to `"value"'.
  647.  
  648. Once the element's value is stored, `awk' has no record of whether it
  649. was stored with a single index or a sequence of indices.  The two
  650. expressions `foo[5,12]' and `foo[5 SUBSEP 12]' always have the same
  651. value.
  652.  
  653. The default value of `SUBSEP' is not a comma; it is the string
  654. `"\034"', which contains a nonprinting character that is unlikely to
  655. appear in an `awk' program or in the input data.
  656.  
  657. The usefulness of choosing an unlikely character comes from the fact
  658. that index values that contain a string matching `SUBSEP' lead to
  659. combined strings that are ambiguous.  Suppose that `SUBSEP' is a
  660. comma; then `foo["a,b", "c"]' and `foo["a", "b,c"]' will be
  661. indistinguishable because both are actually stored as `foo["a,b,c"]'.
  662. Because `SUBSEP' is `"\034"', such confusion can actually happen only
  663. when an index contains the character `"\034"', which is a rare event.
  664.  
  665. You can test whether a particular index--sequence exists in a
  666. ``multi--dimensional'' array with the same operator `in' used for
  667. single dimensional arrays.  Instead of a single index as the
  668. left--hand operand, write the whole sequence of indices, separated by
  669. commas, in parentheses:
  670.  
  671.      (SUBSCRIPT1, SUBSCRIPT2, ...) in ARRAY
  672.  
  673. The following example treats its input as a two--dimensional array of
  674. fields; it rotates this array 90 degrees clockwise and prints the
  675. result.  It assumes that all lines have the same number of elements.
  676.  
  677.      awk 'BEGIN {
  678.           max_nf = max_nr = 0
  679.      }
  680.      
  681.      {
  682.           if (max_nf < NF)
  683.                max_nf = NF
  684.           max_nr = NR
  685.           for (x = 1; x <= NF; x++)
  686.                vector[x, NR] = $x
  687.      }
  688.      
  689.      END {
  690.           for (x = 1; x <= max_nf; x++) {
  691.                for (y = max_nr; y >= 1; --y)
  692.                     printf("%s ", vector[x, y])
  693.                printf("\n")
  694.           }
  695.      }'
  696.  
  697. When given the input:
  698.  
  699.      1 2 3 4 5 6
  700.      2 3 4 5 6 1
  701.      3 4 5 6 1 2
  702.      4 5 6 1 2 3
  703.  
  704. it produces:
  705.  
  706.      4 3 2 1
  707.      5 4 3 2
  708.      6 5 4 3
  709.      1 6 5 4
  710.      2 1 6 5
  711.      3 2 1 6
  712.  
  713.  
  714. 
  715. File: gawk-info,  Node: Multi-scanning,  Prev: Multi-dimensional,  Up: Arrays
  716.  
  717. Scanning Multi--dimensional Arrays
  718. ==================================
  719.  
  720. There is no special `for' statement for scanning a
  721. ``multi--dimensional'' array; there cannot be one, because in truth
  722. there are no multi--dimensional arrays or elements; there is only a
  723. multi--dimensional *way of accessing* an array.
  724.  
  725. However, if your program has an array that is always accessed as
  726. multi--dimensional, you can get the effect of scanning it by
  727. combining the scanning `for' statement (*note Scanning an Array::.)
  728. with the `split' built--in function (*note String Functions::.).  It
  729. works like this:
  730.  
  731.      for (combined in ARRAY) {
  732.        split (combined, separate, SUBSEP)
  733.        ...
  734.      }
  735.  
  736. This finds each concatenated, combined index in the array, and splits
  737. it into the individual indices by breaking it apart where the value
  738. of `SUBSEP' appears.  The split--out indices become the elements of
  739. the array `separate'.
  740.  
  741. Thus, suppose you have previously stored in `ARRAY[1, "foo"]'; then
  742. an element with index `"1\034foo"' exists in ARRAY.  (Recall that the
  743. default value of `SUBSEP' contains the character with code 034.) 
  744. Sooner or later the `for' statement will find that index and do an
  745. iteration with `combined' set to `"1\034foo"'.  Then the `split'
  746. function will be called as follows:
  747.  
  748.      split ("1\034foo", separate, "\034")
  749.  
  750. The result of this is to set `separate[1]' to 1 and `separate[2]' to
  751. `"foo"'.  Presto, the original sequence of separate indices has been
  752. recovered.
  753.  
  754.  
  755. 
  756. File: gawk-info,  Node: Built-in,  Next: User-defined,  Prev: Arrays,  Up: Top
  757.  
  758. Built--in functions
  759. *******************
  760.  
  761. "Built--in" functions are functions always available for your `awk'
  762. program to call.  This chapter defines all the built--in functions
  763. that exist; some of them are mentioned in other sections, but they
  764. are summarized here for your convenience.  (You can also define new
  765. functions yourself.  *Note User-defined::.)
  766.  
  767. In most cases, any extra arguments given to built--in functions are
  768. ignored.  The defaults for omitted arguments vary from function to
  769. function and are described under the individual functions.
  770.  
  771. The name of a built--in function need not be followed immediately by
  772. the opening left parenthesis of the arguments; whitespace is allowed.
  773. However, it is wise to write no space there, since user--defined
  774. functions do not allow space.
  775.  
  776. When a function is called, expressions that create the function's
  777. actual parameters are evaluated completely before the function call
  778. is performed.  For example, in the code fragment:
  779.  
  780.      i = 4
  781.      j = myfunc(i++)
  782.  
  783. the variable `i' will be set to 5 before `myfunc' is called with a
  784. value of 4 for its actual parameter.
  785.  
  786. * Menu:
  787.  
  788. * Numeric Functions::  Functions that work with numbers,
  789.                        including `int', `sin' and `rand'.
  790.  
  791. * String Functions::   Functions for string manipulation,
  792.                        such as `split', `match', and `sprintf'.
  793.  
  794. * I/O Functions::      Functions for files and shell commands
  795.  
  796.  
  797. 
  798. File: gawk-info,  Node: Numeric Functions,  Next: String Functions,  Up: Built-in
  799.  
  800. Numeric Built--in Functions
  801. ===========================
  802.  
  803. The general syntax of the numeric built--in functions is the same for
  804. each.  Here is an example of that syntax:
  805.  
  806.      awk '# Read input records containing a pair of points: x0, y0, x1, y1.
  807.           # Print the points and the distance between them.
  808.           { printf "%f %f %f %f %f\n", $1, $2, $3, $4,
  809.                   sqrt(($2-$1) * ($2-$1) + ($4-$3) * ($4-$3)) }'
  810.  
  811. This calculates the square root of a calculation that uses the values
  812. of the fields.  It then prints the first four fields of the input
  813. record and the result of the square root calculation.
  814.  
  815. Here is the full list of numeric built--in functions:
  816.  
  817. `int(X)'
  818.      This gives you the integer part of X, truncated toward 0.  This
  819.      produces the nearest integer to X, located between X and 0.
  820.  
  821.      For example, `int(3)' is 3, `int(3.9)' is 3, `int(-3.9)' is -3,
  822.      and `int(-3)' is -3 as well.
  823.  
  824. `sqrt(X)'
  825.      This gives you the positive square root of X.  It reports an
  826.      error if X is negative.
  827.  
  828. `exp(X)'
  829.      This gives you the exponential of X, or reports an error if X is
  830.      out of range.  The range of values X can have depends on your
  831.      machine's floating point representation.
  832.  
  833. `log(X)'
  834.      This gives you the natural logarithm of X, if X is positive;
  835.      otherwise, it reports an error.
  836.  
  837. `sin(X)'
  838.      This gives you the sine of X, with X in radians.
  839.  
  840. `cos(X)'
  841.      This gives you the cosine of X, with X in radians.
  842.  
  843. `atan2(Y, X)'
  844.      This gives you the arctangent of Y/X, with both in radians.
  845.  
  846. `rand()'
  847.      This gives you a random number.  The values of `rand()' are
  848.      uniformly--distributed between 0 and 1.  The value is never 0
  849.      and never 1.
  850.  
  851.      Often you want random integers instead.  Here is a user--defined
  852.      function you can use to obtain a random nonnegative integer less
  853.      than N:
  854.  
  855.           function randint(n) {
  856.                return int(n * rand())
  857.           }
  858.  
  859.      The multiplication produces a random real number at least 0, and
  860.      less than N.  We then make it an integer (using `int') between 0
  861.      and `N-1'.
  862.  
  863.      Here is an example where a similar function is used to produce
  864.      random integers between 1 and N:
  865.  
  866.           awk '
  867.           # Function to roll a simulated die.
  868.           function roll(n) { return 1 + int(rand() * n) }
  869.           
  870.           # Roll 3 six--sided dice and print total number of points.
  871.           {
  872.                 printf("%d points\n", roll(6)+roll(6)+roll(6))
  873.           }'
  874.  
  875.      *Note* that `rand()' starts generating numbers from the same
  876.      point, or "seed", each time you run `awk'.  This means that the
  877.      same program will produce the same results each time you run it.
  878.      The numbers are random within one `awk' run, but predictable
  879.      from run to run.  This is convenient for debugging, but if you
  880.      want a program to do different things each time it is used, you
  881.      must change the seed to a value that will be different in each
  882.      run.  To do this, use `srand'.
  883.  
  884. `srand(X)'
  885.      The function `srand(X)' sets the starting point, or "seed", for
  886.      generating random numbers to the value X.
  887.  
  888.      Each seed value leads to a particular sequence of ``random''
  889.      numbers.  Thus, if you set the seed to the same value a second
  890.      time, you will get the same sequence of ``random'' numbers again.
  891.  
  892.      If you omit the argument X, as in `srand()', then the current
  893.      date and time of day are used for a seed.  This is the way to
  894.      get random numbers that are truly unpredictable.
  895.  
  896.      The return value of `srand()' is the previous seed.  This makes
  897.      it easy to keep track of the seeds for use in consistently
  898.      reproducing sequences of random numbers.
  899.  
  900.  
  901. 
  902. File: gawk-info,  Node: String Functions,  Next: I/O Functions,  Prev: Numeric Functions,  Up: Built-in
  903.  
  904. Built--in Functions for String Manipulation
  905. ===========================================
  906.  
  907. `index(IN, FIND)'
  908.      This searches the string IN for the first occurrence of the
  909.      string FIND, and returns the position where that occurrence
  910.      begins in the string IN.  For example:
  911.  
  912.           awk 'BEGIN { print index("peanut", "an") }'
  913.  
  914.      prints `3'.  If FIND is not found, `index' returns 0.
  915.  
  916. `length(STRING)'
  917.      This gives you the number of characters in STRING.  If STRING is
  918.      a number, the length of the digit string representing that
  919.      number is returned.  For example, `length("abcde")' is 5. 
  920.      Whereas, `length(15 * 35)' works out to 3.  How?  Well, 15 * 35
  921.      = 525, and 525 is then converted to the string `"525"', which
  922.      has three characters.
  923.  
  924. `match(STRING, REGEXP)'
  925.      The `match' function searches the string, STRING, for the
  926.      longest, leftmost substring matched by the regular expression,
  927.      REGEXP.  It returns the character position, or "index", of where
  928.      that substring begins (1, if it starts at the beginning of
  929.      STRING).  If no match if found, it returns 0.
  930.  
  931.      The `match' function sets the special variable `RSTART' to the
  932.      index.  It also sets the special variable `RLENGTH' to the
  933.      length of the matched substring.  If no match is found, `RSTART'
  934.      is set to 0, and `RLENGTH' to -1.
  935.  
  936.      For example:
  937.  
  938.           awk '{
  939.                  if ($1 == "FIND")
  940.                    regex = $2
  941.                  else {
  942.                    where = match($0, regex)
  943.                    if (where)
  944.                      print "Match of", regex, "found at", where, "in", $0
  945.                  }
  946.           }'
  947.  
  948.      This program looks for lines that match the regular expression
  949.      stored in the variable `regex'.  This regular expression can be
  950.      changed.  If the first word on a line is `FIND', `regex' is
  951.      changed to be the second word on that line.  Therefore, given:
  952.  
  953.           FIND fo*bar
  954.           My program was a foobar
  955.           But none of it would doobar
  956.           FIND Melvin
  957.           JF+KM
  958.           This line is property of The Reality Engineering Co.
  959.           This file was created by Melvin.
  960.  
  961.       `awk' prints:
  962.  
  963.           Match of fo*bar found at 18 in My program was a foobar
  964.           Match of Melvin found at 26 in This file was created by Melvin.
  965.  
  966. `split(STRING, ARRAY, FIELD_SEPARATOR)'
  967.      This divides STRING up into pieces separated by FIELD_SEPARATOR,
  968.      and stores the pieces in ARRAY.  The first piece is stored in
  969.      `ARRAY[1]', the second piece in `ARRAY[2]', and so forth.  The
  970.      string value of the third argument, FIELD_SEPARATOR, is used as
  971.      a regexp to search for to find the places to split STRING.  If
  972.      the FIELD_SEPARATOR is omitted, the value of `FS' is used. 
  973.      `split' returns the number of elements created.
  974.  
  975.      The `split' function, then, splits strings into pieces in a
  976.      manner similar to the way input lines are split into fields. 
  977.      For example:
  978.  
  979.           split("auto-da-fe", a, "-")
  980.  
  981.      splits the string `auto-da-fe' into three fields using `-' as
  982.      the separator.  It sets the contents of the array `a' as follows:
  983.  
  984.           a[1] = "auto"
  985.           a[2] = "da"
  986.           a[3] = "fe"
  987.  
  988.      The value returned by this call to `split' is 3.
  989.  
  990. `sprintf(FORMAT, EXPRESSION1,...)'
  991.      This returns (without printing) the string that `printf' would
  992.      have printed out with the same arguments (*note Printf::.).  For
  993.      example:
  994.  
  995.           sprintf("pi = %.2f (approx.)", 22/7)
  996.  
  997.      returns the string `"pi = 3.14 (approx.)"'.
  998.  
  999. `sub(REGEXP, REPLACEMENT_STRING, TARGET_VARIABLE)'
  1000.      The `sub' function alters the value of TARGET_VARIABLE.  It
  1001.      searches this value, which should be a string, for the leftmost
  1002.      substring matched by the regular expression, REGEXP, extending
  1003.      this match as far as possible.  Then the entire string is
  1004.      changed by replacing the matched text with REPLACEMENT_STRING. 
  1005.      The modified string becomes the new value of TARGET_VARIABLE.
  1006.  
  1007.      This function is peculiar because TARGET_VARIABLE is not simply
  1008.      used to compute a value, and not just any expression will do: it
  1009.      must be a variable, field or array reference, so that `sub' can
  1010.      store a modified value there.  If this argument is omitted, then
  1011.      the default is to use and alter `$0'.
  1012.  
  1013.      For example:
  1014.  
  1015.           str = "water, water, everywhere"
  1016.           sub(/at/, "ith", str)
  1017.  
  1018.      sets `str' to `"wither, water, everywhere"', by replacing the
  1019.      leftmost, longest occurrence of `at' with `ith'.
  1020.  
  1021.      The `sub' function returns the number of substitutions made
  1022.      (either one or zero).
  1023.  
  1024.      The special character, `&', in the replacement string,
  1025.      REPLACEMENT_STRING, stands for the precise substring that was
  1026.      matched by REGEXP.  (If the regexp can match more than one
  1027.      string, then this precise substring may vary.)  For example:
  1028.  
  1029.           awk '{ sub(/candidate/, "& and his wife"); print }'
  1030.  
  1031.      will change the first occurrence of ``candidate'' to ``candidate
  1032.      and his wife'' on each input line.
  1033.  
  1034.      The effect of this special character can be turned off by
  1035.      preceding it with a backslash (`\&').  To include a backslash in
  1036.      the replacement string, it too must be preceded with a (second)
  1037.      backslash.
  1038.  
  1039.      Note: if you use `sub' with a third argument that is not a
  1040.      variable, field or array element reference, then it will still
  1041.      search for the pattern and return 0 or 1, but the modified
  1042.      string is thrown away because there is no place to put it.  For
  1043.      example:
  1044.  
  1045.           sub(/USA/, "United States", "the USA and Canada")
  1046.  
  1047.      will indeed produce a string `"the United States and Canada"',
  1048.      but there will be no way to use that string!
  1049.  
  1050. `gsub(REGEXP, REPLACEMENT_STRING, TARGET_VARIABLE)'
  1051.      This is similar to the `sub' function, except `gsub' replaces
  1052.      *all* of the longest, leftmost, *non--overlapping* matching
  1053.      substrings it can find.  The ``g'' in `gsub' stands for
  1054.      "global", which means replace *everywhere*.  For example:
  1055.  
  1056.           awk '{ gsub(/Britain/, "United Kingdom"); print }'
  1057.  
  1058.      replaces all occurrences of the string `Britain' with `United
  1059.      Kingdom' for all input records.
  1060.  
  1061.      The `gsub' function returns the number of substitutions made. 
  1062.      If the variable to be searched and altered, TARGET_VARIABLE, is
  1063.      omitted, then the entire input record, `$0', is used.
  1064.  
  1065.      The characters `&' and `\' are special in `gsub' as they are in
  1066.      `sub' (see immediately above).
  1067.  
  1068. `substr(STRING, START, LENGTH)'
  1069.      This returns a LENGTH--character--long substring of STRING,
  1070.      starting at character number START.  The first character of a
  1071.      string is character number one.  For example,
  1072.      `substr("washington", 5, 3)' returns `"ing"'.
  1073.  
  1074.      If LENGTH is not present, this function returns the whole suffix
  1075.      of STRING that begins at character number START.  For example,
  1076.      `substr("washington", 5)' returns `"ington"'.
  1077.  
  1078.  
  1079. 
  1080. File: gawk-info,  Node: I/O Functions,  Prev: String Functions,  Up: Built-in
  1081.  
  1082. Built--in Functions for I/O to Files and Commands
  1083. =================================================
  1084.  
  1085. `close(FILENAME)'
  1086.      Close the file FILENAME.  The argument may alternatively be a
  1087.      shell command that was used for redirecting to or from a pipe;
  1088.      then the pipe is closed.
  1089.  
  1090.      *Note Close Input::, regarding closing input files and pipes. 
  1091.      *Note Close Output::, regarding closing output files and pipes.
  1092.  
  1093. `system(COMMAND)'
  1094.      The system function allows the user to execute operating system
  1095.      commands and then return to the `awk' program.  The `system'
  1096.      function executes the command given by the string value of
  1097.      COMMAND.  It returns, as its value, the status returned by the
  1098.      command that was executed.  This is known as returning the "exit
  1099.      status".
  1100.  
  1101.      For example, if the following fragment of code is put in your
  1102.      `awk' program:
  1103.  
  1104.           END {
  1105.                system("mail -s 'awk run done' operator < /dev/null")
  1106.           }
  1107.  
  1108.      the system operator will be sent mail when the `awk' program
  1109.      finishes processing input and begins its end--of--input
  1110.      processing.
  1111.  
  1112.      Note that much the same result can be obtained by redirecting
  1113.      `print' or `printf' into a pipe.  However, if your `awk' program
  1114.      is interactive, this function is useful for cranking up large
  1115.      self--contained programs, such as a shell or an editor.
  1116.  
  1117.  
  1118. 
  1119. File: gawk-info,  Node: User-defined,  Next: Special,  Prev: Built-in,  Up: Top
  1120.  
  1121. User--defined Functions
  1122. ***********************
  1123.  
  1124. Complicated `awk' programs can often be simplified by defining your
  1125. own functions.  User--defined functions can be called just like
  1126. built--in ones (*note Function Calls::.), but it is up to you to
  1127. define them--to tell `awk' what they should do.
  1128.  
  1129. * Menu:
  1130.  
  1131. * Definition Syntax::   How to write definitions and what they mean.
  1132. * Function Example::    An example function definition and what it does.
  1133. * Function Caveats::    Things to watch out for.
  1134. * Return Statement::    Specifying the value a function returns.
  1135.  
  1136.  
  1137. 
  1138. File: gawk-info,  Node: Definition Syntax,  Next: Function Example,  Up: User-defined
  1139.  
  1140. Syntax of Function Definitions
  1141. ==============================
  1142.  
  1143. The definition of a function named NAME looks like this:
  1144.  
  1145.      function NAME (PARAMETER-LIST) {
  1146.           BODY-OF-FUNCTION
  1147.      }
  1148.  
  1149. A valid function name is like a valid variable name: a sequence of
  1150. letters, digits and underscores, not starting with a digit.
  1151.  
  1152. Such function definitions can appear anywhere between the rules of
  1153. the `awk' program.  The general format of an `awk' program, then, is
  1154. now modified to include sequences of rules *and* user--defined
  1155. function definitions.
  1156.  
  1157. The function definition need not precede all the uses of the function.
  1158. This is because `awk' reads the entire program before starting to
  1159. execute any of it.
  1160.  
  1161. The PARAMETER-LIST is a list of the function's "local" variable
  1162. names, separated by commas.  Within the body of the function, local
  1163. variables refer to arguments with which the function is called.  If
  1164. the function is called with fewer arguments than it has local
  1165. variables, this is not an error; the extra local variables are simply
  1166. set as the null string.
  1167.  
  1168. The local variable values hide or "shadow" any variables of the same
  1169. names used in the rest of the program.  The shadowed variables are
  1170. not accessible in the function definition, because there is no way to
  1171. name them while their names have been taken away for the local
  1172. variables.  All other variables used in the `awk' program can be
  1173. referenced or set normally in the function definition.
  1174.  
  1175. The local variables last only as long as the function is executing. 
  1176. Once the function finishes, the shadowed variables come back.
  1177.  
  1178. The BODY-OF-FUNCTION part of the definition is the most important
  1179. part, because this is what says what the function should actually *do*.
  1180. The local variables exist to give the body a way to talk about the
  1181. arguments.
  1182.  
  1183. Functions may be "recursive", i.e., they can call themselves, either
  1184. directly, or indirectly (via calling a second function that calls the
  1185. first again).
  1186.  
  1187. The keyword `function' may also be written `func'.
  1188.  
  1189.  
  1190. 
  1191. File: gawk-info,  Node: Function Example,  Next: Function Caveats,  Prev: Definition Syntax,  Up: User-defined
  1192.  
  1193. Function Definition Example
  1194. ===========================
  1195.  
  1196. Here is an example of a user--defined function, called `myprint',
  1197. that takes a number and prints it in a specific format.
  1198.  
  1199.      function myprint(num)
  1200.      {
  1201.           printf "%6.3g\n", num
  1202.      }
  1203.  
  1204. To illustrate, let's use the following `awk' rule to use, or "call",
  1205. our `myprint' function:
  1206.  
  1207.      $3 > 0     { myprint($3) }'
  1208.  
  1209. This program prints, in our special format, all the third fields that
  1210. contain a positive number in our input.  Therefore, when given:
  1211.  
  1212.       1.2   3.4   5.6   7.8
  1213.       9.10 11.12 13.14 15.16
  1214.      17.18 19.20 21.22 23.24
  1215.  
  1216. this program, using our function to format the results, will print:
  1217.  
  1218.         5.6
  1219.        13.1
  1220.        21.2
  1221.  
  1222. Here is a rather contrived example of a recursive function.  It
  1223. prints a string backwards:
  1224.  
  1225.      function rev (str, len) {
  1226.          if (len == 0) {
  1227.              printf "\n"
  1228.              return
  1229.          }
  1230.          printf "%c", substr(str, len, 1)
  1231.          rev(str, len - 1)
  1232.      }
  1233.  
  1234.  
  1235. 
  1236. File: gawk-info,  Node: Function Caveats,  Next: Return Statement,  Prev: Function Example,  Up: User-defined
  1237.  
  1238. Caveats of Function Calling
  1239. ===========================
  1240.  
  1241. *Note* that there cannot be any blanks between the function name and
  1242. the left parenthesis of the argument list, when calling a function. 
  1243. This is so `awk' can tell you are not trying to concatenate the value
  1244. of a variable with the value of an expression inside the parentheses.
  1245.  
  1246. When a function is called, it is given a *copy* of the values of its
  1247. arguments.  This is called "passing by value".  The caller may use a
  1248. variable as the expression for the argument, but the called function
  1249. does not know this: all it knows is what value the argument had.  For
  1250. example, if you write this code:
  1251.  
  1252.      foo = "bar"
  1253.      z = myfunc(foo)
  1254.  
  1255. then you should not think of the argument to `myfunc' as being ``the
  1256. variable `foo'''.  Instead, think of the argument as the string
  1257. value, `"bar"'.
  1258.  
  1259. If the function `myfunc' alters the values of its local variables,
  1260. this has no effect on any other variables.  In particular, if
  1261. `myfunc' does this:
  1262.  
  1263.      function myfunc (win) {
  1264.        print win
  1265.        win = "zzz"
  1266.        print win
  1267.      }
  1268.  
  1269. to change its first argument variable `win', this *does not* change
  1270. the value of `foo' in the caller.  The role of `foo' in calling
  1271. `myfunc' ended when its value, `"bar"', was computed.  If `win' also
  1272. exists outside of `myfunc', this definition will not change it--that
  1273. value is shadowed during the execution of `myfunc' and cannot be seen
  1274. or changed from there.
  1275.  
  1276. However, when arrays are the parameters to functions, they are *not*
  1277. copied.  Instead, the array itself is made available for direct
  1278. manipulation by the function.  This is usually called "passing by
  1279. reference".  Changes made to an array parameter inside the body of a
  1280. function *are* visible outside that function.  *This can be very
  1281. dangerous if you don't watch what you are doing.*  For example:
  1282.  
  1283.      function changeit (array, ind, nvalue) {
  1284.           array[ind] = nvalue
  1285.      }
  1286.      
  1287.      BEGIN {
  1288.                 a[1] = 1 ; a[2] = 2 ; a[3] = 3
  1289.                 changeit(a, 2, "two")
  1290.                 printf "a[1] = %s, a[2] = %s, a[3] = %s\n", a[1], a[2], a[3]
  1291.            }
  1292.  
  1293. will print `a[1] = 1, a[2] = two, a[3] = 3', because the call to
  1294. `changeit' stores `"two"' in the second element of `a'.
  1295.  
  1296.  
  1297. 
  1298. File: gawk-info,  Node: Return Statement,  Prev: Function Caveats,  Up: User-defined
  1299.  
  1300. The `return' statement
  1301. ======================
  1302.  
  1303. The body of a user--defined function can contain a `return' statement.
  1304. This statement returns control to the rest of the `awk' program.  It
  1305. can also be used to return a value for use in the rest of the `awk'
  1306. program.  It looks like:
  1307.  
  1308.      `return EXPRESSION'
  1309.  
  1310. The EXPRESSION part is optional.  If it is omitted, then the returned
  1311. value is undefined and, therefore, unpredictable.
  1312.  
  1313. A `return' statement with no value expression is assumed at the end
  1314. of every function definition.  So if control reaches the end of the
  1315. function definition, then the function returns an unpredictable value.
  1316.  
  1317. Here is an example of a user--defined function that returns a value
  1318. for the largest number among the elements of an array:
  1319.  
  1320.      function maxelt (vec,   i, ret) {
  1321.           for (i in vec) {
  1322.                if (ret == "" || vec[i] > ret)
  1323.                     ret = vec[i]
  1324.           }
  1325.           return ret
  1326.      }
  1327.  
  1328. You call `maxelt' with one argument, an array name.  The local
  1329. variables `i' and `ret' are not intended to be arguments; while there
  1330. is nothing to stop you from passing two or three arguments to
  1331. `maxelt', the results would be strange.
  1332.  
  1333. When writing a function definition, it is conventional to separate
  1334. the parameters from the local variables with extra spaces, as shown
  1335. above in the definition of `maxelt'.
  1336.  
  1337. Here is a program that uses, or calls, our `maxelt' function.  This
  1338. program loads an array, calls `maxelt', and then reports the maximum
  1339. number in that array:
  1340.  
  1341.      awk '
  1342.      function maxelt (vec,   i, ret) {
  1343.           for (i in vec) {
  1344.                if (ret == "" || vec[i] > ret)
  1345.                     ret = vec[i]
  1346.           }
  1347.           return ret
  1348.      }
  1349.      
  1350.      # Load all fields of each record into nums.
  1351.      {
  1352.                for(i = 1; i <= NF; i++)
  1353.                     nums[NR, i] = $i
  1354.      }
  1355.      
  1356.      END {
  1357.           print maxelt(nums)
  1358.      }'
  1359.  
  1360. Given the following input:
  1361.  
  1362.       1 5 23 8 16
  1363.      44 3 5 2 8 26
  1364.      256 291 1396 2962 100
  1365.      -6 467 998 1101
  1366.      99385 11 0 225
  1367.  
  1368. our program tells us (predictably) that:
  1369.  
  1370.      99385
  1371.  
  1372. is the largest number in our array.
  1373.  
  1374.  
  1375. 
  1376. File: gawk-info,  Node: Special,  Next: Sample Program,  Prev: User-defined,  Up: Top
  1377.  
  1378. Special Variables
  1379. *****************
  1380.  
  1381. Most `awk' variables are available for you to use for your own
  1382. purposes; they will never change except when your program assigns
  1383. them, and will never affect anything except when your program
  1384. examines them.
  1385.  
  1386. A few variables have special meanings.  Some of them `awk' examines
  1387. automatically, so that they enable you to tell `awk' how to do
  1388. certain things.  Others are set automatically by `awk', so that they
  1389. carry information from the internal workings of `awk' to your program.
  1390.  
  1391. Most of these variables are also documented in the chapters where
  1392. their areas of activity are described.
  1393.  
  1394. * Menu:
  1395.  
  1396. * User-modified::  Special variables that you change to control `awk'.
  1397.  
  1398. * Auto-set::       Special variables where `awk' gives you information.
  1399.  
  1400.