On 22.03.18 14:58, Steve Litt wrote: > Hi all, > > Awk has two kinds of variables: scalars which are strings or ints or > floats, and arrays. Arrays are more like LUA tables or Python dicts or > Perl hashes in that you can use any scalar as a subscript. > Multidimensional arrays are doable but require care and attention. > > The following code crashes, complaining that you're using array a in a > scalar context: > > a[1] = "whatever" > b = a
May one humbly suggest that it doesn't really "crash", but fatally errors on that highly illegal syntax shoved at it. ;-) > A deepcopy operation is the only real way to copy an array in awk. So > I've written deepcopy.awk as a demonstration of a working awk deepcopy > function. See the code at > http://troubleshooters.com/codecorn/awk/stuff/deepcopy.awk It is dangerous to post an opinion based only on decades old recollections, but I think that can be done very simply. I.e. an awk associative array ought to copy so long as we transfer both key and content, needing just one line of awk. Yep, too simple not to work first off, here embellished with a demo framework: #!/bin/bash gawk ' BEGIN { # Populate a 2-dimensional array: a["fred","x"] = 1 ; a["jim","x"] = 2 ; a["bob","x"] = 7 ; a["jill","x"] = 42 a["fred","y"] = 8 ; a["jim","y"] = 9 ; a["bob","y"] = 14 ; a["jill","y"] = 49 #-------------------------------------- for (i in a) b[i] = a[i] # <- This is the entire array copy code #-------------------------------------- a["bob","x"] = 6 # Modify array a in one dimension. a["jill","y"] = 742 # Modify array a in the other dimension. printf("Array a:\n") # Demonstrate that for (i in a) print i,a[i] # array a printf("\nArray b:\n") # is not for (i in b) print i,b[i] # array b. } ' As the "for (i in ..." just walks a hash, sorted output would need a sort to be run prior to the print. With a 2 dimensional array, the walk sequences differ, but the original array is faithfully copied into another. How to prettify the 2-subscript left column in the output isn't instantly coming back to me, even though it is only early evening, but the straightforward array copy is shown to work fine for more than one dimension. I hope that's useful. Erik _______________________________________________ Dng mailing list [email protected] https://mailinglists.dyne.org/cgi-bin/mailman/listinfo/dng
