如何检查变量是否为数组? [英] How to check if a variable is an array?
问题描述
我正在使用PROCINFO及其sorted_in索引,以便能够
I was playing with PROCINFO and its sorted_in index to be able to control the array transversal.
然后我想知道PROCINFO
的内容是什么,所以我决定仔细研究一下并打印其值:
Then I wondered what are the contents of PROCINFO
, so I decided to go through it and print its values:
$ awk 'BEGIN {for (i in PROCINFO) print i, PROCINFO[i]}'
ppid 7571
pgrpid 14581
api_major 1
api_minor 1
group1 545
gid 545
group2 1000
egid 545
group3 10004
awk: cmd. line:1: fatal: attempt to use array `PROCINFO["identifiers"]' in a scalar context
如您所见,它破裂是因为-至少有一个项目本身也是数组.
As you see, it breaks because there is -at least- one item that it is also an array itself.
快速的解决方法是跳过这一步:
The fast workaround is to skip this one:
awk 'BEGIN {for (i in PROCINFO) {if (i!="identifiers") {print i, PROCINFO[i]}}}'
但是它看起来有些古怪,并且想要类似的东西
However it looks a bit hacky and would like to have something like
awk 'BEGIN {for (i in PROCINFO) {if (!(a[i] is array)) {print i, PROCINFO[i]}}}'
^^^^^^^^^^^^^^^^
由于没有类似type()
函数的功能来确定变量是数组还是标量,所以我想知道:有没有办法检查元素是否为数组?
Since there is not a thing like a type()
function to determine if a variable is an array or a scalar, I wonder: is there any way to check if an element is an array?
我在想类似使用for
进行操作并捕获可能的错误,但我不知道如何.
I was thinking in something like going through it with a for
and catching the possible error, but I don't know how.
$ awk 'BEGIN{a[1]=1; for (i in a) print i}'
1
$ awk 'BEGIN{a=1; for (i in a) print i}'
awk: cmd. line:1: fatal: attempt to use scalar `a' as an array
$ awk 'BEGIN{a[1]=1; print a}'
awk: cmd. line:1: fatal: attempt to use array `a' in a scalar context
推荐答案
在GNU Awk中,有一个答案,但是推荐的方法取决于您所运行的版本.感谢 fedorqui 的更新!
In GNU Awk, there's an answer, but the recommended approach depends on what version you are running. Thanks to fedorqui for the update!
从2017年10月发布的GNU Awk 4.2开始,有一个新功能typeof()
对此进行检查,如beta版本的发行说明所述:
From GNU Awk 4.2, released in October 2017, there is a new function typeof()
to check this, as indicated in the release notes from the beta release:
- 新的typeof()函数可用于指示变量或数组元素是数组,正则表达式,字符串还是数字.不推荐使用isarray()函数,而推荐使用typeof().
现在您可以说:
$ awk 'BEGIN { a[1] = "a"; print typeof(a) }'
array
并执行以下检查:
$ awk 'BEGIN { a = "a"; if (typeof(a) == "array") print "yes" }'
$ awk 'BEGIN { a[1] = "a"; if (typeof(a) == "array") print "yes" }'
yes
在旧版本中,您可以使用 isarray()
:
In older versions, you can use isarray()
:
$ awk 'BEGIN { a = "a"; if (isarray(a)) print "yes" }'
$ awk 'BEGIN { a[1] = "a"; if (isarray(a)) print "yes" }'
yes
在手册页中:
isarray(x)
Return true if x is an array, false otherwise.
这篇关于如何检查变量是否为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!