In addition to providing a number of standard functions (described in the manual page for awk), the awk language allows you to define your own custom functions. The syntax for a function declaration is:
function function_name(parameter1 [, parameter2, ...]) { |
action |
} |
Because variables are in the global scope except for function parameters, if you want to define a local variable in a function, you must declare it as an extra parameter to the function. You do not have to pass in a value. If you do not declare the variable as a parameter, it affects execution outside of the function and its value is persistent across multiple invocations of the function.
For example, this function takes two parameters, subtracts them, and then adds one (1):
function subtractAndAddOne(a, b, c) { |
c = 1 |
return (a-b+c); |
} |
BEGIN { |
print subtractAndAddOne(3, 2); |
} |
Important: When you call a function, you must not put a space before the opening parenthesis. In awk, a space is used for string concatenation, so adding a space is likely to cause a syntax error. However, it might instead result in rather strange behavior in certain contexts.
Last updated: 2008-04-08