3

I have an array like this ...

a["a"]                = "aa"
a["b"]                = "ab"
a["c"]                = "ac"
a["d"]["a"]           = "ada"
a["d"]["b"]["a"]      = "adba"
a["e"]["a"]["a"]["a"] = "aeaaa"

... and want to clone it

clone(b, a)

This is what I tried so far :

function clone(lhs, rhs){

    for (i in rhs) {
        if (typeof(arr[i]) == "array"){
            clone(lhs[i], rhs[i])
        } else {
            lhs[i] = rhs[i]
        }
    }
}

But this clearly doesn't work because b["d"] is not created before that a["d"]["a"] is asigned to b["d"]["a"]. The second problem is that b["d"] should be typed as array.

4

You need to initialise the subarray before cloning into it:

function clone(lhs, rhs) {
    for (i in rhs) {
        if (isarray(rhs[i])) {
            lhs[i][1] = ""
            delete lhs[i][1]
            clone(lhs[i], rhs[i])
        } else {
            lhs[i] = rhs[i]
        }
    }
}

The write-value-then-delete it trick is mentioned in the gawk man page.

(I also fixed the array detection, using isarray.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.