Modules and Exporter
| package | |
| One file, one module | |
| Export with Exporter | |
| use and require |
package
A package is a namespace for subroutines and variables. Declare one at the top of a file and every name below it belongs to that package until the next declaration.
package My::Text;
use strict;
use warnings;
sub trim {
my ($s) = @_;
$s =~ s/^\s+|\s+$//g;
return $s;
}
1;
Two colons separate the parts of a package name, and each part is capitalized by convention. The final 1; matters: a module must return a true value, because use checks the result.
One file, one module
The package name decides the file path. My::Text lives in My/Text.pm, directly under a library folder that the program adds to its search path.
lib/My/Text.pm
use lib "lib";
use My::Text qw(trim);
print My::Text::trim(" hi "), "\n"; # hi
Without an export list the full name My::Text::trim is required. That is explicit and always works, but the shorter form below reads better in real code.
Export with Exporter
Exporter is in the core and gives a module an import method. List the public functions in @EXPORT_OK, which means the caller may ask for them by name, and put private helpers outside the list.
package My::Text;
use strict;
use warnings;
use Exporter 'import';
our @EXPORT_OK = qw(trim);
sub trim {
my ($s) = @_;
$s =~ s/^\s+|\s+$//g;
return $s;
}
1;
With that in place the caller writes use My::Text qw(trim); and then trim($s). The explicit empty list use My::Text (); imports nothing and keeps every name qualified.
use and require
use runs at compile time and calls import; require runs at runtime and only loads the file. Practically every module wants use, because imports must exist before the rest of the file is compiled.
use My::Text qw(trim); # compile time, imports trim
require My::Text; # runtime, no import
For code that may not be installed, wrap a require in eval and check $@. That is how a script offers an optional feature without making the module a hard dependency.
Next: CPAN and cpanm
Article author: Arthur Isaev