This section discusses some aspects of variable shadowing. Feel free to skip it upon first reading.
The “shadowing” concept is important to know for several reasons.
Using global identifiers (names) locally can lead to very difficult
debugging, it complicates writing, reading and maintaining source code,
and it decreases the portability, (sharing or reuse) of a library of
awk
functions.
It is a best practice to consistently use a naming convention, such as “global variable and function names start with a capital letter and local names begin with lowercase one.” This also makes programs easier to follow (see Naming Library Function Global Variables).
The gawk
extension SYMTAB
provides indirect access
to global variables that are or may be shadowed (see SYMTAB
in Built-in Variables That Convey Information). For example:
... foo = "global value" ... function test(x, foo) { # use global value of foo as default foo = (x > 0) ? SYMTAB["foo"] : "local value" ... }
The gawk
namespace extension
provides robust handling of potential name collisions with global
variables and functions (see Namespaces in gawk
). Namespaces
are useful to prevent shadowing by providing identifiers that are
common to a group of functions and effectively shadowed from being
referenced by global functions (See FUNCTAB
in Built-in Variables That Convey Information.)
Finally, a shadowing caveat: Variables local to a function are not
“global” to anything. SYMTAB
elements refer to all global
variables and arrays, but not to local variables and arrays.
If a function A(argA, localA)
calls another function B()
,
the two variables local to A()
are not accessible in
function B()
or any other function. The global/local distinction
is also important to remember when passing arguments to a function called
indirectly (see Indirect Function Calls).