Previous: , Up: Library Functions   [Contents][Index]


10.7 Traversing Arrays of Arrays

Arrays of Arrays, described how gawk provides arrays of arrays. In particular, any element of an array may be either a scalar, or another array. The isarray() function (see Type Functions) lets you distinguish an array from a scalar. The following function, walk_array(), recursively traverses an array, printing each element’s indices and value. You call it with the array and a string representing the name of the array:

function walk_array(arr, name,      i)
{
    for (i in arr) {
        if (isarray(arr[i]))
            walk_array(arr[i], (name "[" i "]"))
        else
            printf("%s[%s] = %s\n", name, i, arr[i])
    }
}

It works by looping over each element of the array. If any given element is itself an array, the function calls itself recursively, passing the subarray and a new string representing the current index. Otherwise, the function simply prints the element’s name, index, and value. Here is a main program to demonstrate:

BEGIN {
    a[1] = 1
    a[2][1] = 21
    a[2][2] = 22
    a[3] = 3
    a[4][1][1] = 411
    a[4][2] = 42

    walk_array(a, "a")
}

When run, the program produces the following output:

$ gawk -f walk_array.awk
-| a[4][1][1] = 411
-| a[4][2] = 42
-| a[1] = 1
-| a[2][1] = 21
-| a[2][2] = 22
-| a[3] = 3

Walking an array and processing each element is a general-purpose operation. You might want to consider generalizing the walk_array() function by adding an additional parameter named process.

Then, inside the loop, instead of simply printing the array element’s index and value, use the indirect function call syntax (see Indirect Calls) on process, passing it the index and the value.

When calling walk_array(), you would pass the name of a user-defined function that expects to receive an index and a value, and then processes the element.


Previous: , Up: Library Functions   [Contents][Index]