ArrayLength

Posix does not define a way to get the length of an array, while you could use a loop to count the elements the usual strategy is to keep track of the length yourself.

   #using a counter
   a[n++]="foo"
   a[n++]="bar"
   printf "the length of a is %d\n",n 

   #remember that split returns a value
   n=split("foo bar",a)
   printf "the length of a is %d\n",n 


   # loop on the elements of a
   # you don't always no need to know the length!
   for (i in a) print a[i] 

Some awk implementations (gnu awk, true awk) allow you to use length on an array see AwkFeatureComparison. Up to now (ie gawk 3.1.6) you cannot use length on an array passed as an argument to a function:

#!/usr/bin/gawk -f
function foo(array){
    # does not work! you need to pass the length as an extra argument
    printf "In a function, the length of array is %d\n", length(array)
}
BEGIN{
    array[1]="foo";array[2]="bar"
    printf "the length of array is %d\n", length(array)
    foo(array)
}

The above code results in:

the length of array is 2
gawk: ./length.gawk:3: fatal: attempt to use array `array (from array)' in a scalar context

This problem is fixed in the gawk-stable CVS version available from savannah.gnu.org.