In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?
At the very core, the file extension you use makes no difference as to how perl
interprets those files.
However, putting modules in .pm
files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD
and you put it in a directory Example/Plot/FourD.pm
in a path in your @INC
, then use
and require
will do the right thing when given the package name as in use Example::Plot::FourD
.
The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with
1;
unless you're sure it'll return true otherwise. But it's better just to put the1;
, in case you add more statements.If
EXPR
is a bareword, therequire
assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.
All use
does is to figure out the filename from the package name provided, require
it in a BEGIN
block and invoke import
on the package. There is nothing preventing you from not using use
but taking those steps manually.
For example, below I put the Example::Plot::FourD
package in a file called t.pl
, loaded it in a script in file s.pl
.
C:\Temp> cat t.pl
package Example::Plot::FourD;
use strict; use warnings;
sub new { bless {} => shift }
sub something { print "something\n" }
"Example::Plot::FourD"
C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;
BEGIN {
require 't.pl';
}
my $p = Example::Plot::FourD->new;
$p->something;
C:\Temp> s
something
This example shows that module files do not have to end in 1
, any true value will do.