Next: , Previous: , Up: User-defined   [Contents][Index]

9.2.2 Function Definition Examples

Here is an example of a user-defined function, called myprint(), that takes a number and prints it in a specific format:

function myprint(num)
     printf "%6.3g\n", num

To illustrate, here is an awk rule that uses our myprint function:

$3 > 0     { myprint($3) }

This program prints, in our special format, all the third fields that contain a positive number in our input. Therefore, when given the following input:

 1.2   3.4    5.6   7.8
 9.10 11.12 -13.14 15.16
17.18 19.20  21.22 23.24

this program, using our function to format the results, prints:


This function deletes all the elements in an array:

function delarray(a,    i)
    for (i in a)
       delete a[i]

When working with arrays, it is often necessary to delete all the elements in an array and start over with a new list of elements (see Delete). Instead of having to repeat this loop everywhere that you need to clear out an array, your program can just call delarray. (This guarantees portability. The use of ‘delete array’ to delete the contents of an entire array is a recent60 addition to the POSIX standard.)

The following is an example of a recursive function. It takes a string as an input parameter and returns the string in backwards order. Recursive functions must always have a test that stops the recursion. In this case, the recursion terminates when the starting position is zero, i.e., when there are no more characters left in the string.

function rev(str, start)
    if (start == 0)
        return ""

    return (substr(str, start, 1) rev(str, start - 1))

If this function is in a file named rev.awk, it can be tested this way:

$ echo "Don't Panic!" |
> gawk --source '{ print rev($0, length($0)) }' -f rev.awk
-| !cinaP t'noD

The C ctime() function takes a timestamp and returns it in a string, formatted in a well-known fashion. The following example uses the built-in strftime() function (see Time Functions) to create an awk version of ctime():

# ctime.awk
# awk version of C ctime(3) function

function ctime(ts,    format)
    format = "%a %b %e %H:%M:%S %Z %Y"
    if (ts == 0)
        ts = systime()       # use current time as default
    return strftime(format, ts)



Late in 2012.

Next: , Previous: , Up: User-defined   [Contents][Index]