Associative array/Iteration: Difference between revisions

→‎{{header|AWK}}: gawk allows sorting
(→‎{{header|AWK}}: gawk allows sorting)
Line 321:
 
=={{header|AWK}}==
In AWK "arrays" are always associative arrays, and the only way to iterate over them is by keys (''indexes'' in the AWK terminology), in undefined order.
 
<lang awk>BEGIN {
a["hello"] = 1
Line 328 ⟶ 327:
a["!"] = 3
 
# iterate over keys, undefined order
for(key in a) {
print key, a[key]
}
}</lang>
 
As AWK was often used in (Bourne) shell scripts,
sorting was done by a pipe of two awk programs and the sort command.
Today, 'gawk' allows to set the order of iteration:
<lang awk>BEGIN {
a["hello"] = 1
a["world"] = 2
a["!"] = 3
PROCINFO["sorted_in"] = "@ind_str_asc" # controls index order
# iterate over keys, indices as strings sorted ascending
for(key in a) {
print key, a[key]
Anonymous user