Perl module

From Wikipedia, the free encyclopedia

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 in Perl's Plain Old Documentation format. 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


 # The 'package' command gives the name of the module or class.
 
 package Hello::World;
 use strict;
 use warnings;
 
 # By convention, a module's version number is stored in 
 # $ModuleName::VERSION; certain forms of the "use" built-in depend 
 # on this variable being defined.
 
 our $VERSION = "1.0";
 
 # Lines starting with an equal sign indicate embedded POD 
 # documentation.  POD sections end with an =cut directive, and can 
 # be intermixed almost freely with normal code.
 
 =head1 NAME
 
 Hello::World - An encapsulation of a commonly output message
 
 =head1 SYNOPSIS
 
    use Hello::World;
    my $hw = new Hello::World();
    $hw->print();
 
 =head1 DESCRIPTION
 
 This is an object-oriented library which can print the famous "H.W."
 message.
 
 =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 to_string
 
 Returns the greeting as a string
 
 =cut
 
 sub to_string {
    my $self = shift;
    return $self->{message};
 }
 
 =item print
 
 Outputs the greeting to STDOUT
 
 =cut
 
 sub print {
    my $self = shift;
    print $self->to_string(),"\n";
 }
 
 =back
 
 =head1 AUTHOR
 
 Joe Hacker <joe@joehacker.org>
 
 =cut
 
 # The lone "1;" at the end of the file indicates that the module 
 # has been successfully initialized.  Some modules contain code 
 # that runs as soon as the module is compiled, before the program 
 # that included it is finished compiling; they can arrange to return
 # a non-true value if something goes wrong.
 1;

In other languages