问题
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
- The new
typeof()
function can be used to indicate if a variable or array element is an array, regexp, string or number. Theisarray()
function is deprecated in favor oftypeof()
.
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:
- 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