1

In one answer I collected field values and used them as key of two associative arrays.

awk '{a[$2]++;b[$2]++}
     END {
       for(i in a) printf "a : %s\n", i ;
       for(i in b) printf "b : %s\n", i
     }' some_file.txt

I assumed the keys of those two arrays will be accessed in the same order, since they are exactly the same set.

The GNU Awk User's Guide describes the behaviour of awk as below:

The order in which elements of the array are accessed by this statement is determined by the internal arrangement of the array elements within awk and in standard awk cannot be controlled or changed.

So I understand the order can't be predicted, but is that to say it won't be deterministic and context independent?


Update. In view of the accepted answer, I edited my referenced answer to fit the behaviour of awk.

Amessihel
  • 5,891
  • 3
  • 16
  • 40

1 Answers1

4

It will be deterministic in as much as the order of indices visited by the in operator will always be the same for 1 array, but you cannot assume the traversal order will be the same for the elements of 1 array as they are for a different array even if the elements are the same and were inserted in the same order since how the array elements are stored is implementation dependent and for all we know there's a time, or available memory, or some other non-obvious aspect to that mechanism.

If you need an order, you need to implement that order. If you have such similar arrays and need to print bs values in the order the indices are stored in a then you'd write for (i in a) print b[i]

Ed Morton
  • 188,023
  • 17
  • 78
  • 185