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:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting the true value at the end of a module file
- Exporting many names by default with @EXPORT
- 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: