15.8 Including A File Without Changing The Namespace

As mentioned at the end of Including Other Files into Your Program, files included with @include are treated as if they had ‘@namespace "awk"’ at their beginning. Sometimes, though, this behavior is undesirable.

Consider, for example, the case where you have some significant functions in one namespace:

@namespace "mylib"

function major_func1(a, b, c) { ... }
function major_func2(a, b, c) { ... }
...

From another namespace, you want to call these functions, frequently:

@namespace "myproj1"
function job1(a, b, c) {
    ...
    if (mylib::major_func1(a, b, c))
        ...
    else if (mylib::major_func2(a, b, c))
        ...
    ...
}
... and so on ...

Using the ‘mylib::’ prefix everywhere starts to get painful.

You might then try to write some forwarding functions, which you would @include in each namespace. For example, something like this in a file named mylib_forward.awk:

function major_func1(a, b, c)
{
    return mylib::major_func1(a, b, c)
}

function major_func2(a, b, c)
{
    return mylib::major_func2(a, b, c)
}

You might then try to @include this file in each namespace:

@namespace "myproj1"
@include "mylib_forward.awk"

function job1(a, b, c) {
    ...
    if (major_func1(a, b, c))       # calls forwarding function
        ...
    else if (major_func2(a, b, c))  # ditto
        ...
    ...
}
...

@namespace "myproj2"
@include "mylib_forward.awk"
...

But this won’t work, since @include resets the namespace to ‘awk’.

For this reason, @nsinclude was added. It works exactly the same as @include, but it does not change the namespace:

@namespace "myproj1"
@nsinclude "mylib_forward.awk"

function job1(a, b, c) {
    ...
    if (major_func1(a, b, c))       # calls forwarding function
        ...
    else if (major_func2(a, b, c))  # ditto
        ...
    ...
}
...

@namespace "myproj2"
@nsinclude "mylib_forward.awk"
...

This will work the way we want it to.