Back at 2012/11/27 15:00:13, I left a note on YJL --wiki about Awk’s PROCINFO["sorted_in"]. I was trying to have a sorting order when using:

for (idnx in array)
  do something

According to Controlling Array Traversal:

By default, the order in which a ‘for (indx in array)’ loop scans an array is not defined; it is generally based upon the internal implementation of arrays inside awk.

It means by default, the idnx in each iteration might not be what you have in mind, and I think this was when I first encountered before I found PROCINFO["sorted_in"] as a solution for an Awk script, which, however, I can’t find where I actually use it even I do remember printing out elements of an array but they were in an order that I didn’t expect.

In order to have array elements coming in desire order, PROCINFO["sorted_in"] can be of use, which has the following valid options to set with:

"@unsorted"
The default option as described above.
"my_cmp_func"

Appointing a custom sorting function:

function comp_func(i1, v1, i2, v2)
{
    compare elements 1 and 2 in some fashion
    return < 0; 0; or > 0
}
"@SORT_AS_ORDER"

There are ten valid sorting options:

"@ind_str_asc" "@ind_str_desc"
"@ind_num_asc" "@ind_num_desc"
"@val_type_asc" "@val_type_desc"
"@val_str_asc" "@val_str_desc"
"@val_num_asc" "@val_num_desc"

They can be broken down to three parts:

SORT Treated AS ORDER by
ind Index str string asc ascending
val Value num number dec descending
  type type  

Scanning the array’s SORT as AS data type and order by ORDER. When an order is required, just do as the following:

PROCINFO["sorted_in"] = "@SORT_AS_ORDER"
for (idnx in data)
  do something

Bear in mind, PROCINFO["sorted_in"]:

  1. Affects globally and
  2. Changes within a loop will not be effective.

If you want to physically sort the array other than the order of looping through, in GNU Awk, there are also the built-in asort and asorti functions, see Sorting Array Values and Indices with gawk. It could be a portability issue across different implementations of Awk if you want to use them.