Perl-Python Tutorial: Writing A Module

2005-01-19

Python

A programer can define functions, save it in a file, then later on load the file and use these functions. For example, save the following line in a file and name it “mymodule.py”.

def f1(n): return n+1

To load the file, use import “import mymodule”, then to call the function, use “moduleName.functionName”. Example:

import mymodule           # import the module
print mymodule.f1(5)      # calling its function
print mymodule.__name__   # list its functions and variables

Reference: Python Doc↗.

Reference: Python Doc↗.

Perl

In the following, i show you how to write a library in perl by a example.

Save the following 3 lines in a file and name it “mymodule.pm”.

package mymodule;    # declaring the module
sub f1($){$_[0]+1}   # module body
1                    # module must return a true value

Then, call it like the following way:

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.

In Perl, there are 2 different concepts for a set of code that resides in a file: “module” and “package”.

A “module” is simply a file of perl code. To load a module, use “require myFileName”. It is similar to “include” in C and PHP. A module file normally has suffix “.pl”.

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 filename;” and must return a value true (any number, string, as the last line will do).

Perl's module was there before it had a real library system. You should just write packages.

Reference: perldoc perlmod↗.

Reference: perldoc -f use↗.

Reference: perldoc -f require↗.


See also:


Page created: 2005-01.
© 2005 by Xah Lee.
Xah Signet