The intent of this question is to post a canonical answer to a problem with a non-obvious solution - copying arrays of arrays (requires GNU awk for arrays of arrays).
Given an array of arrays such as shown in the gawk manual on the section about traversing arrays:
BEGIN {
a[1] = 1
a[2][1] = 21
a[2][2] = 22
a[3] = 3
a[4][1][1] = 411
a[4][2] = 42
walk_array(a, "a")
}
function walk_array(arr, name, i)
{
for (i in arr) {
if (isarray(arr[i]))
walk_array(arr[i], (name "[" i "]"))
else
printf("%s[%s] = %s\n", name, i, arr[i])
}
}
how would you write a copy_array
function that can handle arrays of arrays to copy an existing array to a new array such that a subsequent call to walk_array()
for the newly copied array would output the same values for the new array as for the original, i.e. so that this:
BEGIN {
a[1] = 1
a[2][1] = 21
a[2][2] = 22
a[3] = 3
a[4][1][1] = 411
a[4][2] = 42
walk_array(a, "a")
copy_array(a, b)
print "----------"
walk_array(b, "b")
}
would output:
a[1] = 1
a[2][1] = 21
a[2][2] = 22
a[3] = 3
a[4][1][1] = 411
a[4][2] = 42
----------
b[1] = 1
b[2][1] = 21
b[2][2] = 22
b[3] = 3
b[4][1][1] = 411
b[4][2] = 42