Function in awk 
Author Message
 Function in awk


Does nayboby know how to wrtite a function in awk

Thanks for your help

Mon, 05 Nov 2001 03:00:00 GMT  
 Function in awk


>Does nayboby know how to wrtite a function in awk

The standard response would be - read the manual. Here's a purposefully very
brief example with comments intended to describe but not explain.

# test action
{ printf("Input number: %d\tfactorial = %d\n", $1, factorial($1) }
# factorial(n) returns the brute force n! value. Argument is truncated to
function factorial(n,  r) # r is a 'local' variable
  if (n < 0) {
    printf("factorial: n = %g -- whatcha think this is, a gamma function?!\n",
    exit # functions can call exit
  r = 1
  for (n = int(n); n > 1; --n) r *= n
  return r


Functions are pretty much the same as pattern-actions except that the function
declaration appears instead of a pattern before the opening left brace.

Unlike pattern-actions, functions must be called in order to execute their
code. If you want the function to return a value, you must use the 'return'
statement. Otherwise, functions can act as subprocedures, returning nothing.

You can use arrays as function arguments, but they must be instantiated as
arrays first. Also, arrays are passed by reference, scalar arguments are passed
by value. Finally, in a function if you refer to a variable that's not included
in the function's declaration's argument list, awk considers it a global
variable, creating it if it doesn't already exist. This is how awk functions
can produce side effects.

Mon, 05 Nov 2001 03:00:00 GMT  
 [ 2 post ] 

 Relevant Pages 

1. Inverse trigonometric functions in awk

2. Format functions in AWK

3. Lookup function in awk - answer

4. Unescape function in Awk

5. No ABS function in Awk?

6. Date functions for awk?

7. Functions in AWK

8. How can i do Recursive function in AWK?

9. way of sharing functions in AWK

10. APLish AWK functions

11. return multiple values from an awk function?

12. Including awk (mawk) functions in a script


Powered by phpBB® Forum Software