21.07.2015 Views

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

GAWK: Effective AWK Programming

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8: Functions 157}a[1] = 1; a[2] = 2; a[3] = 3changeit(a, 2, "two")printf "a[1] = %s, a[2] = %s, a[3] = %s\n",a[1], a[2], a[3]prints ‘a[1] = 1, a[2] = two, a[3] = 3’, because changeit stores "two" in thesecond element of a.Some awk implementations allow you to call a function that has not been defined. Theyonly report a problem at runtime when the program actually tries to call the function. Forexample:BEGIN {if (0)foo()elsebar()}function bar() { ... }# note that ‘foo’ is not definedBecause the ‘if’ statement will never be true, it is not really a problem that foo has notbeen defined. Usually, though, it is a problem if a program calls an undefined function.If ‘--lint’ is specified (see Section 11.2 [Command-Line Options], page 177), gawkreports calls to undefined functions.Some awk implementations generate a runtime error if you use the next statement (seeSection 6.4.8 [The next Statement], page 108) inside a user-defined function. gawk does nothave this limitation.8.2.4 The return StatementThe body of a user-defined function can contain a return statement. This statement returnscontrol to the calling part of the awk program. It can also be used to return a value for usein the rest of the awk program. It looks like this:return [expression]The expression part is optional. If it is omitted, then the returned value is undefined,and therefore, unpredictable.A return statement with no value expression is assumed at the end of every functiondefinition. So if control reaches the end of the function body, then the function returns anunpredictable value. awk does not warn you if you use the return value of such a function.Sometimes, you want to write a function for what it does, not for what it returns. Sucha function corresponds to a void function in C or to a procedure in Pascal. Thus, it maybe appropriate to not return any value; simply bear in mind that if you use the return valueof such a function, you do so at your own risk.The following is an example of a user-defined function that returns a value for the largestnumber among the elements of an array:function maxelt(vec,{i, ret)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!