How to check the type of an awk variable?

一世执手 提交于 2021-02-07 04:20:10

问题


The Beta release of gawk 4.2.0, available in http://www.skeeve.com/gawk/gawk-4.1.65.tar.gz is a major release, with many significant new features.

I previously asked about What is the behaviour of FS = " " in GNU Awk 4.2?, and now I noticed the brand new typeof() function to deprecate isarray():

Changes from 4.1.4 to 4.2.0

  1. The new typeof() function can be used to indicate if a variable or array element is an array, regexp, string or number. The isarray() function is deprecated in favor of typeof().

I could cover four cases: string, number, array and unassigned:

$ awk 'BEGIN {print typeof("a")}'
string
$ awk 'BEGIN {print typeof(1)}'
number
$ awk 'BEGIN {print typeof(a[1])}'
unassigned
$ awk 'BEGIN {a[1]=1; print typeof(a)}'
array

However, I struggle to get "regexp" since none of my attempts reach that and always yield "number":

$ awk 'BEGIN {print typeof(/a/)}'
number
$ awk 'BEGIN {print typeof(/a*/)}'
number
$ awk 'BEGIN {print typeof(/a*d/)}'
number
$ awk 'BEGIN {print typeof(!/a*d/)}'
number
$ awk -v var="/a/" 'BEGIN{print typeof(var)}'
string
$ awk -v var=/a/ 'BEGIN{print typeof(var)}'
string

How can I get a variable to be defined as "regexp"?

I noticed the previous bullet:

  1. Gawk now supports strongly typed regexp constants. Such constants look like @/.../. You can assign them to variables, pass them to functions, use them in ~, !~ and the case part of a switch statement. More details are provided in the manual.

And tried a bit, but with no luck:

$ awk -v pat=@/a/ '{print typeof(pat)}' <<< "bla ble"
string

回答1:


typeof(/a/) is running typeof() on the result of $0 ~ /a/ which is a number. I haven't tried this yet myself but I'd expect this to be what you're looking for:

typeof(@/a/)

and

var = @/a/
typeof(var)

So this works:

$ awk 'BEGIN {print typeof(@/a/)}'
regexp

$ awk 'BEGIN {var=@/a/; print typeof(var)}'
regexp


来源:https://stackoverflow.com/questions/46662790/how-to-check-the-type-of-an-awk-variable

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