This section introduces some terminology for consistently describing
variables and their types. It relies on the typeof() function
provided by gawk (not presented yet; see Getting Type Information)
to demonstrate the subjects under discussion.
Variables in awk don’t receive a type until the first time they’re used.
Until that time, variables are untyped:
$ gawk 'BEGIN { print typeof(a) }'
⊣ untyped
A variable can be used as an array:
$ gawk 'BEGIN { a[1] = 42; print typeof(a) }'
⊣ array
Once a variable becomes an array, it cannot be used as a scalar, that is, a variable with just a single value:
$ gawk 'BEGIN { a[1] = 42; print a }'
⊣ gawk: cmd. line:2: fatal: attempt to use array `a' in a scalar context
Simply using an untyped variable by itself in a statement causes it to become a scalar:
$ gawk 'BEGIN {
> print "a is", typeof(a)
> a # use it by itself!
> print "a is now", typeof(a)
> }'
⊣ a is untyped
⊣ a is now unassigned
The same is true as soon as you use an untyped variable in an expression or pass it to a built-in function:36
$ gawk 'BEGIN {
> print "a is", typeof(a)
> b = length(a)
> print "a is now", typeof(a)
> }'
⊣ a is untyped
⊣ a is now unassigned
Scalars, in turn, have several subtypes. The following are the most important: unassigned, numeric, and string:
$ gawk 'BEGIN {
> a = b # b was never given a value, a and b both unassigned
> print "type of a is", typeof(a), "and type of b is", typeof(b)
>
> c = 42
> print "type of c is", typeof(c)
>
> d = "don\47t panic"
> print "type of d is", typeof(d)'
> }'
⊣ type of a is unassigned and type of b is unassigned
⊣ type of c is number
⊣ type of d is string