MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

Python & Perl: Writing A Module

Xah Lee,

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〕.

# -*- coding: utf-8 -*-
# python

def f1(n):
    return n+1

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

# -*- coding: utf-8 -*-
# python

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

http://docs.python.org/lib/typesmodules.html

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〕.

# -*- coding: utf-8 -*-
# perl

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:

# -*- 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.

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.

blog comments powered by Disqus