Perl module: Difference between revisions

Content deleted Content added
No edit summary
Rewrote the sample module for better formatting, and included a few explanitory comments.
Line 1:
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|POD]] 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.
Line 15 ⟶ 16:
''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
Line 29 ⟶ 47:
message.
=head1 SYNOPSIS
 
Use like this:
use Hello:World;
my $hw = new Hello:World();
$hw->print();
 
=head1 METHODS
Line 55 ⟶ 65:
}
=item toStringto_string
Returns the greeting as a string
Line 61 ⟶ 71:
=cut
sub toStringto_string {
my $self = shift;
return $self->{message};
Line 81 ⟶ 91:
=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;
----