AWK Error: Attempt to use array in a scalar context

匿名 (未验证) 提交于 2019-12-03 08:48:34

问题:

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.

回答1:

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.



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!