AWK error: trying to use array in scalar context

I am learning AWK. Here is a simple piece of code that I tried breaking a string into an array and scrolling through it.

BEGIN { split("a,b,c", a, ","); for(i = 1; i <= length(a); i++) { print a[i]; } } 

When I run this code, I get the following error:

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

However, if I change the for statement to for (i in a) , it works fine. Trying to understand what this means, Google Googling, I see several forums (for example: [1] ) talking about awk bugs . It would be great if AWK gurus can help me understand what the error message means.

+4
source share
2 answers

length expects a string argument. You are passing an array. The error message tells you that you are using an array in which a scalar is expected.

+5
source
 BEGIN { count = split("a,b,c", a, ","); for(i = 1; i <= count; i++) { print a[i]; } } 

Additionally, length(ARRAY) working on my version of awk (GNU awk 4.0.1), but the documentation says that the behavior is non-standard.

+3
source

Source: https://habr.com/ru/post/1433401/


All Articles