← Back to Perl Course | Chapter 7: Object-Oriented Perl | Lesson 1 of 7

Packages and namespaces

A package is a named container that keeps its subroutines and variables separate from everyone else's.

In this page:

  1. Packages and namespaces

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

perl
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
Common Mistakes
  1. Forgetting that a subroutine in another package needs its full name
  2. Thinking package names and file names must be the same
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.