在awk函数主体中数组长度失败 [英] array length fails in awk function body

查看:91
本文介绍了在awk函数主体中数组长度失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无权访问其他awk版本来检查此问题的普遍性.

I don't have access to other awk versions to check the generality of this issue.

$ awk --version
GNU Awk 3.1.5

考虑这个简单的测试

$ awk 'function f(x) {x[1]} BEGIN{f(x); print length(x)}'
1

可以正常工作,但是在函数主体中打印长度失败

works as expected, however printing the length in the function body fails

$ awk 'function f(x) {x[1]; print length(x)} BEGIN{f(x)}'
awk: fatal: attempt to use array `x (from x)' in a scalar context

获得函数体中数组长度的唯一方法似乎是对元素for(i in x) c++

the only way to get the length of an array in a function body seems to be counting the elements for(i in x) c++

这受此 answer

推荐答案

length()曾经是用于查找字符串中字符数的.然后,gawk对其进行了修改,以找到数组中元素的数量.然后POSIX采用了gawk方法,今天我们到了这里,所有人都兴高采烈地将字符串或数组作为length()的参数.

Once upon a time length() was for finding the number of characters in a string. Then gawk modified it to also find the number of elements in an array. Then POSIX adopted the gawk approach and here we are today with all awks cheerfully taking strings or arrays as arguments to length().

您遇到的问题在现代awk版本中不会发生,这是gawk 3.1.5和3.1.6中的错误,请参见

What you're experiencing doesn't happen in modern awk versions, it was a bug in gawk 3.1.5 and 3.1.6, see https://lists.gnu.org/archive/html/bug-gnu-utils/2008-03/msg00028.html

这篇关于在awk函数主体中数组长度失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆