vk239
vk239

Reputation: 1054

AWK Error: Attempt to use array in a scalar context

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.

Upvotes: 8

Views: 15894

Answers (2)

j.w.r
j.w.r

Reputation: 4239

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.

Upvotes: 4

William Pursell
William Pursell

Reputation: 212404

length expects a string argument. You are passing it an array. The error message is telling you that you are using an array where a scalar is expected.

Upvotes: 9

Related Questions