10.0 Modular Programming with Functions
10.1. The Importance of Functions
Functions are fundamental building blocks for creating modular, reusable, and maintainable code. A large program can be broken down into smaller, self-contained functions that perform specific tasks. AWK provides a rich library of built-in functions for common operations and also allows programmers to define their own.
10.2. Built-in Functions
AWK comes with a large set of pre-defined functions that are always available. They are generally grouped into the following categories:
- Arithmetic Functions
- String Functions
- Time Functions
- Bit Manipulation Functions
- Miscellaneous Functions
10.3. User-Defined Functions
Creating custom functions is key to managing complexity and promoting code reuse.
- General Syntax:
- The function keyword is required.
- function_name must begin with a letter and can contain letters, numbers, or underscores.
- The parameter list is a comma-separated list of variable names; it can be empty.
- The function body contains the AWK statements that execute when the function is called.
The following example, stored in a file named functions.awk, defines functions to find the minimum and maximum of two numbers and calls them from a main function.
# functions.awk
# Returns minimum number
function find_min(num1, num2){
if (num1 < num2)
return num1
return num2
}
# Returns maximum number
function find_max(num1, num2){
if (num1 > num2)
return num1
return num2
}
# Main function
function main(num1, num2){
# Find minimum number
result = find_min(10, 20)
print “Minimum =”, result
# Find maximum number
result = find_max(10, 20)
print “Maximum =”, result
}
# Script execution starts here
BEGIN {
main(10, 20)
}
Output:
Minimum = 10
Maximum = 20
After processing data internally with functions, it is often necessary to send the results to external files or commands, which we can accomplish with I/O redirection.