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:

   5.6
  21.2

This function deletes all the elements in an array (recall that the extra whitespace signifies the start of the local variable list):

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 section The delete Statement). 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 relatively recent61 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 reverse order. Recursive functions must always have a test that stops the recursion. In this case, the recursion terminates when the input string is already empty:

function rev(str)
{
    if (str == "")
        return ""

    return (rev(substr(str, 2)) substr(str, 1, 1))
}

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

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

The C ctime() function takes a timestamp and returns it as a string, formatted in a well-known fashion. The following example uses the built-in strftime() function (see section 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)
}

You might think that ctime() could use PROCINFO["strftime"] for its format string. That would be a mistake, because ctime() is supposed to return the time formatted in a standard fashion, and user-level code could have changed PROCINFO["strftime"].


Footnotes

(61)

Late in 2012.


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