What is the Difference between .pm
(Perl module) and .pl
(Perl script) file?
Please also tell me why we return 1
from file. If return 2 or anything else, it's not generating any error, so why do we return 1
from Perl module?
pm file, similar to Java and C# where you can have multiple classes in a single file. A module is a . pm file (“pm” means Perl Module). When you import a module with “require” or “use”, you are literally referencing the file name and not the package(s) contained in the file.
A Perl module is a reusable package defined in a library file whose name is the same as the name of the package (with a . pm on the end). A Perl module file called "Foo.pm" might contain statements like this. The functions require and use will load a module.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With