Путеводитель по Руководству Linux

  User  |  Syst  |  Libr  |  Device  |  Files  |  Other  |  Admin  |  Head  |



   gawk    ( 1 )

язык сканирования и обработки шаблонов (pattern scanning and processing language)

USER-DEFINED FUNCTIONS

Functions in AWK are defined as follows:

function name(parameter list) { statements }

Functions execute when they are called from within expressions in either patterns or actions. Actual parameters supplied in the function call are used to instantiate the formal parameters declared in the function. Arrays are passed by reference, other variables are passed by value.

Since functions were not originally part of the AWK language, the provision for local variables is rather clumsy: They are declared as extra parameters in the parameter list. The convention is to separate local variables from real parameters by extra spaces in the parameter list. For example:

function f(p, q, a, b) # a and b are local { ... }

/abc/ { ... ; f(1, 2) ; ... }

The left parenthesis in a function call is required to immediately follow the function name, without any intervening whitespace. This avoids a syntactic ambiguity with the concatenation operator. This restriction does not apply to the built-in functions listed above.

Functions may call each other and may be recursive. Function parameters used as local variables are initialized to the null string and the number zero upon function invocation.

Use return expr to return a value from a function. The return value is undefined if no value is provided, or if the function returns by 'falling off' the end.

As a gawk extension, functions may be called indirectly. To do this, assign the name of the function to be called, as a string, to a variable. Then use the variable as if it were the name of a function, prefixed with an @ sign, like so: function myfunc() { print "myfunc called" ... }

{ ... the_func = "myfunc" @the_func() # call through the_func to myfunc ... } As of version 4.1.2, this works with user-defined functions, built-in functions, and extension functions.

If --lint has been provided, gawk warns about calls to undefined functions at parse time, instead of at run time. Calling an undefined function at run time is a fatal error.

The word func may be used in place of function, although this is deprecated.