Perl: How to Write a Module
Here's to write a module in Perl by a example.
Save the following 3 lines in a file and name it mymodule.pm
.
# -*- coding: utf-8 -*- # perl package mymodule; # declaring the module sub f1($){$_[0]+1} # module body # more code here 1 # module must return a true value
Then, call it like the following way:
# -*- coding: utf-8 -*- # perl use mymodule; # import the module print mymodule::f1(5); # call the function
This is the simplest illustration of writing a package in Perl and calling its function.
Module vs Package
- A “module” is simply a file of Perl code. To load a module, use
require filename
. It is similar to “include” in C and PHP. A module file normally has suffix “.pl”. Perl's module was there before it had a real library system. You should just write packages. - A “package” in Perl is more modern meaning of a library. It is a mechanism of importing functions defined in a external file, using name spaces. Package files has “.pm” as suffix. A package file needs to start with
package name;
and must return a value true (any number, string, as the last line will do).
The word “module” and “package” are often used interchangably. Sometimes in a technical context, the word “module” refers to a file, and the word “package” refers to the namespace.
Module File Path Correspondence
Module/package name corresponds to the file's name/path. For example, if you have a module at
abc.pm
you load it like this:
use abc;
module file can be grouped into directories. If you have a module with subdirs, named:
GameX/sound.pm
you can load it like this
use GameX::sound;
The double colon ::
corresponds to directory separator /
.