Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

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?

like image 468
user380979 Avatar asked Aug 04 '10 05:08

user380979


People also ask

What is a Perl .pm file?

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.

How do I use Perl modules?

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.


1 Answers

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 the 1;, in case you add more statements.

If EXPR is a bareword, the require 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.

like image 110
Sinan Ünür Avatar answered Sep 19 '22 15:09

Sinan Ünür