gawk: Type Functions
1
1 9.1.7 Getting Type Information
1 ------------------------------
1
1 'gawk' provides two functions that let you distinguish the type of a
1 variable. This is necessary for writing code that traverses every
1 element of an array of arrays (⇒Arrays of Arrays), and in other
1 contexts.
1
1 'isarray(X)'
1 Return a true value if X is an array. Otherwise, return false.
1
1 'typeof(X)'
1 Return one of the following strings, depending upon the type of X:
1
1 '"array"'
1 X is an array.
1
1 '"regexp"'
11 X is a strongly typed regexp (⇒Strong Regexp
Constants).
1
1 '"number"'
1 X is a number.
1
1 '"string"'
1 X is a string.
1
1 '"strnum"'
1 X is a number that started life as user input, such as a field
1 or the result of calling 'split()'. (I.e., X has the strnum
1 attribute; ⇒Variable Typing.)
1
1 '"unassigned"'
1 X is a scalar variable that has not been assigned a value yet.
1 For example:
1
1 BEGIN {
1 # creates a[1] but it has no assigned value
1 a[1]
1 print typeof(a[1]) # unassigned
1 }
1
1 '"untyped"'
1 X has not yet been used yet at all; it can become a scalar or
1 an array. The typing could even conceivably differ from run
1 to run of the same program! For example:
1
1 BEGIN {
1 print "initially, typeof(v) = ", typeof(v)
1
1 if ("FOO" in ENVIRON)
1 make_scalar(v)
1 else
1 make_array(v)
1
1 print "typeof(v) =", typeof(v)
1 }
1
1 function make_scalar(p, l) { l = p }
1
1 function make_array(p) { p[1] = 1 }
1
1 'isarray()' is meant for use in two circumstances. The first is when
1 traversing a multidimensional array: you can test if an element is
1 itself an array or not. The second is inside the body of a user-defined
1 function (not discussed yet; ⇒User-defined), to test if a
1 parameter is an array or not.
1
1 NOTE: Using 'isarray()' at the global level to test variables makes
1 no sense. Because you are the one writing the program, you are
1 supposed to know if your variables are arrays or not. And in fact,
1 due to the way 'gawk' works, if you pass the name of a variable
1 that has not been previously used to 'isarray()', 'gawk' ends up
1 turning it into a scalar.
1
1 The 'typeof()' function is general; it allows you to determine if a
1 variable or function parameter is a scalar, an array, or a strongly
1 typed regexp.
1