8.0 Data Structures: Associative Arrays
yields no output.
[jerry]$ awk ‘BEGIN { fruits[“mango”] = “yellow”; fruits[“orange”] = “orange”; \
delete fruits[“orange”]; print fruits[“orange”] }’
8.3. Simulating Multi-Dimensional Arrays
While AWK natively supports only one-dimensional arrays, multi-dimensional arrays can be easily simulated. This is achieved by concatenating the multiple indices into a single string key. By default, AWK uses the built-in SUBSEP variable to join the indices, but any character (like a comma) can be used.
For example, to simulate array[0][0] = 100, you can use the syntax array[“0,0”] = 100.
The following script simulates a 2-D array and prints its elements:
[jerry]$ awk ‘BEGIN { \
array[“0,0”] = 100; array[“0,1”] = 200; array[“0,2”] = 300; \
array[“1,0”] = 400; array[“1,1”] = 500; array[“1,2”] = 600; \
# print array elements \
print “array[0,0] = ” array[“0,0”]; \
print “array[0,1] = ” array[“0,1”]; \
print “array[0,2] = ” array[“0,2”]; \
print “array[1,0] = ” array[“1,0”]; \
print “array[1,1] = ” array[“1,1”]; \
print “array[1,2] = ” array[“1,2”]; }’
Output:
array[0,0] = 100
array[0,1] = 200
array[0,2] = 300
array[1,0] = 400
array[1,1] = 500
array[1,2] = 600
Manipulating data within arrays and variables often requires structured logic, which is provided by AWK’s control flow statements.