< Day Day Up > |
6.23. User -Defined Functions ( nawk )A user-defined function can be placed anywhere in the script that a pattern action rule can be placed. FORMAT function name (parameter, parameter, parameter, ...) { statements return expression (The return statement and expression are optional) } Variables are passed by value and are local to the function where they are used. Only copies of the variables are used. Arrays are passed by address or by reference, so array elements can be directly changed within the function. Any variable used within the function that has not been passed in the parameter list is considered a global variable; that is, it is visible to the entire nawk program, and if changed in the function, is changed throughout the program. The only way to provide local variables within a function is to include them in the parameter list. Such parameters are usually placed at the end of the list. If there is not a formal parameter provided in the function call, the parameter is initially set to null. The return statement returns control and possibly a value to the caller. Example 6.160.(The Command Line Display of grades File before Sort) % cat grades 44 55 66 22 77 99 100 22 77 99 33 66 55 66 100 99 88 45 (The Script) % cat sorter.sc # Scriptname: sorter # It sorts numbers in ascending order 1 function sort (scores, num_elements, temp, i, j) { # temp, i, and j will be local and private, # with an initial value of null. 2 for(i = 2; i <= num_elements ; ++i) { 3 for (j = i; scores [j1] > scores[j]; j){ temp = scores[j] scores[j] = scores[j1] scores[j1] = temp } 4 } 5 } 6 {for (i = 1; i <= NF; i++) grades[i]=$i 7 sort(grades, NF) # Two arguments are passed 8 for(j = 1; j <= NF; ++j) printf("%d ", grades[j]) printf("\n") } (After the Sort) % nawk f sorter.sc grades 22 44 55 66 77 99 22 33 66 77 99 100 45 55 66 88 99 100 EXPLANATION
|
< Day Day Up > |