Perl Modules and namespaces
A module is a container which holds a group of variables and subroutines which can be used in a program. Every module has a public interface, a set of functions and variables.
To use a module into your program, require or use statement can be used, although their semantics are slightly different.
The 'require' statement loads module at runtime to avoid redundant loading of module. The 'use' statement is like require with two added properties, compile time loading and automatic importing.
Namespace is a container of a distinct set of identifiers (variables, functions). A namespace would be like name::variable.
Every piece of Perl code is in a namespace.
In the following code,
Here are two different variables defined as x. the $main::x is a package variable and $x is a lexical variable. Mostly we use lexical variable declared with my keyword and use namespace to separate functions.
In the above code, if we won't use use strict, we'll get a warning message as
The main is the namespace of the current script and of current variable. We have not written anything and yet we are already in the 'main' namespace.
By adding 'use strict', now we got the following error,
In this error, we got a new word 'package'. It indicates that we forgot to use 'my' keyword before declaring variable but actually it indicates that we should provide name of the package the variable resides in.
Perl Switching namespace using package keyword
Look at the following code,
Here we are using package keyword to switch from 'main' namespace to 'two' namespace.
Calling hii() with namespaces returns respective namespaces. Like ,say main::hii(); returns 'main' and say two::hii(); returns 'two'.
Calling hii() without namespace prefix, returns the function that was local to the current namespace. In first time, we were in 'two' namespace. Hence it returned 'two'. In second time, we switched the namespace using package main. Hence it returns 'main'.