You can control the order of array traversal like this:
function cmp_len(i1, v1, i2, v2) {
return length(v1) - length(v2)
}
BEGIN {
b[1] = "alnis"
b[2] = "nis"
b[3] = "connis"
PROCINFO["sorted_in"] = "cmp_len"
for (i in b) {
print b[i]
}
}
I have created my own comparison function and assigned its name to PROCINFO["sorted_in"]
to alter the order in which the elements are traversed.
Testing it out:
$ awk -f script.awk
nis
alnis
connis
You can also pass the name of this function to asort
as a third argument, in order to write the sorted values to a new array:
asort(b, sorted, "cmp_len")
Note that this changes the indices of the array elements but not the order in which they will be traversed with a for (i in sorted)
loop. To loop through the results in the new order, you need to use a "C-style" loop or change PROCINFO["sorted_in"]
as above.