A program contains multiple functionalities, and each functionality can be independently written as a function.
Functions can improve code reusability.
The syntax format for user-defined functions is:
function function_name(argument1, argument2, ...)
{
function body
}
Explanation:
- function_nameIt is the name of the user-defined function. The function name should start with a letter, followed by any combination of digits, letters, or underscores. AWK reserved keywords cannot be used as names of user-defined functions.
- A user-defined function can accept multiple input parameters, and these parameters are separated by commas. Parameters are not mandatory. We can also define functions without any input parameters.
- function bodyIt is the function body part, which contains AWK program code.
In the following example, we implemented two simple functions, which respectively return the minimum and maximum of two numeric values. We called these two functions from the main function main. The code in the file functions.awk is as follows:
# 返回最小值
function find_min(num1, num2)
{
if (num1 < num2)
return num1
return num2
}
# 返回最大值
function find_max(num1, num2)
{
if (num1 > num2)
return num1
return num2
}
# 主函数
function main(num1, num2)
{
# 查找最小值
result = find_min(10, 20)
print "Minimum =", result
# 查找最大值
result = find_max(10, 20)
print "Maximum =", result
}
# 脚本从这里开始执行
BEGIN {
main(10, 20)
}
Executing the functions.awk file gives the following results:
$ awk -f functions.awk Minimum = 10 Maximum = 20