DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Programming with awk

User-defined functions

awk provides user-defined functions. A function is defined as

   function name(argument-list) {
   	statements
   }
The definition can occur anywhere a pattern-action statement can. The argument list is a list of variable names separated by commas; within the body of the function these variables refer to the actual parameters when the function is called. No space must be left between the function name and the left parenthesis of the argument list when the function is called; otherwise it looks like a concatenation. For example, the following program defines and tests the usual recursive factorial function (of course, using some input other than the file countries):
   function fact(n) {
        if (n <= 1)
             return 1
        else
             return n * fact(n-1)
   }
   { print $1 "! is " fact($1) }

Array arguments are passed by reference, as in C, so it is possible for the function to alter array elements or create new ones. Scalar arguments are passed by value, however, so the function cannot affect their values outside. Within a function, formal parameters are local variables, but all other variables are global. (You can have any number of extra formal parameters that are used only as local variables.) The return statement is optional, but the returned value is undefined if it is not included.


Next topic: Some lexical conventions
Previous topic: Arrays

© 2005 The SCO Group, Inc. All rights reserved.
SCO OpenServer Release 6.0.0 -- 02 June 2005