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,

snippet
use strict;
use warnings;
my $x = "Hello";
$main::x = "Bye";
print "$main::x\n";  # Bye
print "$x\n";        # Hello

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

snippet
Name 	"main::x" used only once: possible typo at line..

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,

snippet
Global symbol "$x" requires explicit package name

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,

snippet
use strict;
use warnings;
use 5.010;
sub hii {
    return "main";
}
package two;
sub hii {
    return "two";
} 
say main::hii();   # main
say two::hii();    # two
say hii();         # two
package main;
say main::hii();   # main
say two::hii();    # two
say hii();         # main

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'.

Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +