Alex Rivera | Logout

AWK Error: Attempt to use array in a scalar context

Asked 2012-09-10T15:54:24.797
8

I am learning AWK. Here is a simple code snippet I tried to split a string into an array and iterate through it.

BEGIN {
  split("a,b,c", a, ",");

  for(i = 1; i <= length(a); i++) {
    print a[i];
  }
}

On running this code, I get the following error:

awk: awk.txt:4: fatal: attempt to use array `a' in a scalar context

However, if I change the for statement to for (i in a) it works just fine. On further trying to understand what this means by Googling it, I see a number of forums (eg: [1]) talking about awk bugs. It will be great if AWK gurus here can help me understand what the error message means.

awk
Edit
Report

1 Answer

4
BEGIN {
  count = split("a,b,c", a, ",");

  for(i = 1; i <= count; i++) {
    print a[i];
  }
}

Also, length(ARRAY) works on my version of awk (GNU awk 4.0.1), but the documentation states that the behavior is non-standard.

answered 2012-09-10T16:03:50.860

Your Answer