Perl module

This is an old revision of this page, as edited by Lowellian (talk | contribs) at 12:41, 30 December 2004. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

A Perl module is a discrete component of software for the Perl programming language. A module is distinguished by a unique namespace, e.g. "CGI" or "Net::FTP" or "XML::Parser". By conventions, there is typically one module per file with a .pm extension. A collection of one or more modules, with accompanying documentation and build scripts, compose a package. The Perl community has a sizable library of packages available for search and download via CPAN.

It is common for Perl modules to have embedded documentation. Many modules favor an object-oriented style, but many are procedural instead, especially old modules.

Below is an example of a very simple object-oriented Perl module and a short program which makes use of the module. It is implemented in a dialect of Perl5 which is compatible with Perl 5.6.0 and higher.

helloworld.pl


 #!/usr/bin/perl -w
 use Hello::World;
 my $hello = Hello::World->new();
 $hello->print();

Hello/World.pm


 package Hello::World;
 use strict;
 use warnings;
 our $VERSION = "1.0";
 
 =head1 NAME
 
 Hello::World - An encapsulation of a commonly output message
 =head1 DESCRIPTION
 
 This is an object-oriented library which can print the famous "H.W."
 message.
 
 =head1 SYNOPSIS
 Use like this:
 
    use Hello:World;
    my $hw = new Hello:World();
    $hw->print();
 =head1 METHODS
 
 =over
 
 =item new
 
 Instantiates an object which holds a greeting message.
 
 =cut
 
 sub new {
    my $pkg = shift;
    my $self = bless({
       message => "Hello, world!",
    }, $pkg);
    return $self;
 }
 
 =item toString
 
 Returns the greeting as a string
 
 =cut
 
 sub toString {
    my $self = shift;
    return $self->{message};
 }
 
 =item print
 
 Outputs the greeting to STDOUT
 
 =cut
 
 sub print {
    my $self = shift;
    print $self->toString(),"\n";
 }
 
 =back
 
 =head1 AUTHOR
 
 Joe Hacker
 =cut
 1;