Packages and namespaces
A package is a named container that keeps its subroutines and variables separate from everyone else's.
In this page:
Packages and namespaces
The package statement switches the current namespace, so a subroutine called greet in package Animal is really Animal::greet. Package variables can be reached from outside with their full name, such as $Animal::count. The default package, when you write none, is main, and the __PACKAGE__ token gives the name of the current one.
Note:
A package block, package Name { ... }, limits the scope of the declaration to the braces (available since Perl 5.14).
Example: Packages and namespaces
use strict;
use warnings;
package Greeter {
our $count = 0;
sub hello {
$count++;
return "Hello from " . __PACKAGE__;
}
}
package main;
print Greeter::hello(), "\n";
print Greeter::hello(), "\n";
print "hello called $Greeter::count times\n";
print "current package: ", __PACKAGE__, "\n";
# Output:
# Hello from Greeter
# Hello from Greeter
# hello called 2 times
# current package: main
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that a subroutine in another package needs its full name
- Thinking package names and file names must be the same
- Assuming package variables declared with our are private
Chapter Summary
- package NAME switches the namespace
- Full names look like Package::name
- main is the default package
- __PACKAGE__ gives the current package name
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: