Functions are basic building blocks of a program. AWK allows us to
define our own functions. A large program can be divided into functions
and each function can be written/tested independently. It provides
re-usability of code.Given below is the general format of the user defined function:
function function_name(argument1, argument2, ...)
{
function body
}
In above syntax:function_name is the name of the user defined function. Function name should begin with a letter and rest of the characters can be any combination of numbers, alphabetic characters or underscore. AWK's reserve words cannot be used as function name.
Function can accept multiple arguments separated by comma. Arguments are not mandatory. We can also create a user defined function without any argument.
function body consists of one or more AWK statements.
Let us write two functions which calculates minimum and maximum number and call these functions from another function called main. Our functions.awk file look like this:
# 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)
}
On executing the above code, you get the following result:Minimum = 10 Maximum = 20
No comments:
Post a Comment