Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does sorting for arrays of arrays differ to multidimensional arrays in awk?

Tags:

awk

I have approached the a problem to list a set of items, which have components, which in turn have properties in awk.

I have tried to approach the problem in two ways.

1) Define an array list[item-number,component-number][properties].
2) Define an array list[item-number][component-number][properties].

This was in many ways interesting, as I noticed (2) maintain the order of insertion, while (1) does not. I know arrays are associative in awk and it could very well be a coincidence this happened. However, as the order of insertion is important in my case (and also, I want to learn more about awk), I would like to know if this is what happening and why.

Any ideas? BR Patrik

like image 311
patrik Avatar asked Jan 23 '26 15:01

patrik


1 Answers

Neither approach retains any information on the order of insertion, if it seems like either does then that is just coincidence. If the order of insertion is important to you then you need to write some code to track that order, e.g.

key = foo FS bar
if ( !(key in list) ) {
    keys[++numKeys] = key
}
list[key] = whatever

would give you an array keys[] of the indices in the order they are inserted and an array list[] that maps each key to it's value so you can later do:

for (keyNr=1; keyNr<=numKeys; keyNr++) {
    key = keys[keyNr]
    print list[key]
}

or similar to print the contents of list[] in the order they were inserted.

like image 77
Ed Morton Avatar answered Jan 27 '26 02:01

Ed Morton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!