Perl Modules - Perl Packages and Namespaces

Perl Packages and Namespaces

A running Perl program has a built-in namespace called "main", which is the default name. For example a subroutine called Sub1 can be called as Sub1 or main::Sub1. With a variable the appropriate sigil is placed in front of the namespace; so a scalar variable called $var1 can also be referred to as $main::var1, or even $::var1. Other namespaces can be created at any time.

package Namespace1; $var1 = 1; # created in namespace Namespace1, which is also created if not pre-existing our $var2 = 2; # also created in that namespace; our required if use strict is applied my $var3 = 3; # lexically-scoped my-declared - NOT in any namespace, not even main $Namespace2::var1 = 10; # created in namespace Namespace2, also created if not pre-existing our $Namespace2::var2 = 20; # also created in that namespace my $Namespace2::var3 = 30;#compilation error:my-declared variables CAN'T belong to a package

Package declarations apply package scope till the next package declaration or the end of the block in which the declaration is made.

our $mainVar = 'a'; package Sp1; our $sp1aVar = 'aa'; print "$main::mainVar\t$sp1aVar\n"; # note mainVar needs qualifying package Sp2; our $sp2aVar = 'aaa'; print "$main::mainVar\t$Sp1::sp1aVar\t$sp2aVar\n";# note mainVar and sp1aVar need qualifying package main; print "$mainVar\t$Sp1::sp1aVar\t$Sp2::sp2aVar\n"; # note sp1aVar and sp2aVar need qualifying $mainVar = 'b'; { # NOTE previously created packages and package variables still accessible package Sp1; our $sp1bVar = 'bb'; print "$main::mainVar\t$sp1aVar\t$sp1bVar\n"; # note mainVar needs qualifying { package Sp2; our $sp2bVar = 'bbb'; print "$main::mainVar\t$Sp1::sp1aVar$Sp1::sp1bVar\t$sp2aVar$sp2bVar\n"; } # note mainVar and sp1...Var need qualifying print "$main::mainVar\t$sp1bVar$sp1aVar\t$Sp2::sp2bVar$Sp2::sp2aVar\n"; } # note package Sp1 applies by default # main applies again by default; all package variables still accessible as long as qualified print "$mainVar\t$Sp1::sp1aVar$Sp2::sp2bVar\n";

Read more about this topic:  Perl Modules