Perl module: Difference between revisions

Content deleted Content added
See Talk page Packages and modules
Perl packages and namespaces: Clarified terminology in comments in examples; improved formatting
Line 268:
 
==Perl packages and namespaces==
A running Perl program has a built-in namespace called "<code>main</code>", which is the default name. For example a subroutine called <code>Sub1</code> can be called as <code>Sub1()</code> or <code>main::Sub1()</code>. With a variable the appropriate sigil is placed in front of the namespace; so a scalar variable called <code>$var1</code> can also be referred to as <code>$main::var1</code>, or even <code>$::var1</code>. Other namespaces can be created at any time.
 
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.
<source lang="perl">
package Namespace1;
$var1 = 1; # created in the Namespace1 namespace, 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 - dynamically scoped
</source>
 
Line 283 ⟶ 279:
$Namespace2::$var1 = 10; # created in the Namespace2 namespace, which is also created if not pre-existing
our $Namespace2::var2 = 20; # also created in that namespace
my $Namespace2::var3 = 30; # compilation error, as dynamicallymy-scopeddeclared variablevariables canCAN'T't belong to a package
</source>