← Back to Perl Course | Chapter 8: Modules | Lesson 6 of 7

Writing your own module

A module is a package you can reuse, and Exporter lets it hand chosen functions to its users.

In this page:

  1. Writing your own module

Writing your own module

A module is normally a package saved in a file with the same name plus .pm, but you can also define one directly in a script. Adding use Exporter import lets the package export the names listed in @EXPORT_OK (on request) or @EXPORT (by default). A module file should end with a true value such as 1; so that loading it succeeds.

Note: Prefer @EXPORT_OK over @EXPORT, so users must ask for the names they want and your module does not fill their namespace.

Example: Writing your own module

perl
use strict;
use warnings;

BEGIN {
    package MyMath;
    use Exporter 'import';
    our @EXPORT_OK   = qw(square cube);
    our %EXPORT_TAGS = (all => \@EXPORT_OK);

    sub square { return $_[0] ** 2; }
    sub cube   { return $_[0] ** 3; }
    sub hidden { return "not exported"; }
    $INC{'MyMath.pm'} = 1;
}

use MyMath qw(square cube);

print "square(5) = ", square(5), "\n";
print "cube(3) = ", cube(3), "\n";
print "full name still works: ", MyMath::hidden(), "\n";
print "hidden imported? ", (main->can('hidden') ? "yes" : "no"), "\n";

# Output:
# square(5) = 25
# cube(3) = 27
# full name still works: not exported
# hidden imported? no
Common Mistakes
  1. Forgetting the true value at the end of a module file
  2. Exporting many names by default with @EXPORT
  3. Naming the file differently from the package
Chapter Summary
  • A module is a package in a .pm file
  • Exporter exports names
  • @EXPORT_OK exports on request
  • The file must end with a true value
🔒

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.