views:

86

answers:

2

Hello stack.

I've got following problem with gawk's asorti function:

gawk 'BEGIN{ \

  a[1]=6; \

  a[2]=7; \

  a[3]=8; \

  a[21]=9; \

  a[123]=10; \

  t=asorti(a, o); \

  for (i=1; i<=t; i++) { \

    print i,o[i]; \

  } \

}'

The result is:

1 1

2 123

3 2

4 21

5 3

So it's pretty clear awk, sorted indices in lexicographical order, but awk's doc says (asort(s[, d])):

"The contents of s are sorted using gawk’s normal rules for comparing values..."

However, when I copy indices itself into temp array, and sort that new array using asort(),

it seems ok (using something like):

j=1; for(e in a) { temp[j++] = e; }

Am I DOIN-IT-WRONG, or is it problem with gawk's asorti() ?

+3  A: 

According to the gawk manual: "An important aspect about arrays to remember is that array subscripts are always strings."

Dennis Williamson
THANKS! I've missed that.
GiM
A: 

As a workaround you could use something like this (you may need to adjust the padding):

gawk 'BEGIN { 
  a[1] = 6; a[2] = 7; a[3] = 8; a[21] = 9; a[123] = 10; 
  for (i in a) io[sprintf("%15s", i)] = a[i]
  t = asorti(io, o)
  for (i = 0; ++i <= t;) print i, o[i] + 0
    }'

With Gnu awk you can even preserve the original keys/indexes:

WHINY_USERS=oops gawk 'BEGIN { 
  a[1]=6; a[2]=7; a[3]=8; a[21]=9; a[123]=10; 
  for (i in a) o[sprintf("%15s", i)] = a[i]
  for (i in o) print i + 0, o[i]
    }'
radoulov