Perl module

Last updated

A Perl module is a discrete component of software for the Perl programming language. Technically, it is a particular set of conventions for using Perl's package mechanism that has become universally adopted.[ discuss ]

Contents

A module defines its source code to be in a package (much like a Java package), the Perl mechanism for defining namespaces, e.g. CGI or Net::FTP or XML::Parser; the file structure mirrors the namespace structure (e.g. the source code for Net::FTP is in Net/FTP.pm). Furthermore, a module is the Perl equivalent of the class when object-oriented programming is employed.[ discuss ]

A collection of modules, with accompanying documentation, build scripts, and usually a test suite, composes a distribution. The Perl community has a sizable library of distributions available for search and download via CPAN.

Perl is a language allowing many different styles of programming. A developer is as likely to find a module written in a procedural style (for example, Test::Simple) as object-oriented (e.g. XML::Parser), both are considered equally valid according to what the module needs to do. Modules might also be used to mixin methods (DBIx::Class) or be a pragma (strict.pm) which has an effect immediately upon being loaded. Modules can even be used to alter the syntax of the language. The effect of Perl modules are usually limited to the current scope in which it was loaded.

It is common for Perl modules to have embedded documentation in Perl's Plain Old Documentation format. POD imposes little structure on the author. It is flexible enough to be used to write articles, web pages and even entire books such as Programming Perl. Contrast with javadoc which is specialized to documenting Java classes. By convention, module documentation typically follows the structure of a Unix man page.

The language of Perl is defined by the single implementation (referred to as "perl") and is added to (and in rare occasions taken away from) each new release. For this reason it is important for a module author to be aware what features they're making use of and what the minimum required version of perl is. The code on this page requires perl 5.6.0 which is considered rather old by now.

Examples

What follows are examples of "Hello, World" implemented in different styles of modules. It must be understood that a module is not necessary in Perl; functions and code can be defined and used anywhere. This is just for example purposes. Contrast with Java where a class is always necessary. A real "Hello, World" function would be written like so:

subhello{"Hello, world!\n"}printhello();

or simply printed in one line:

print"Hello, world!\n";

Procedural example

Here is "Hello, World" implemented as a procedural module with a customizable target for the greeting, just to make things interesting. Also included is a short script to illustrate the module's use.

hello_world.pl

#!/usr/bin/perl# Loads the module and imports any functions into our namespace # (defaults to "main") exported by the module.  Hello::World exports# hello() by default.  Exports can usually be controlled by the caller.useHello::World;printhello();# prints "Hello, world!\n"printhello("Milky Way");# prints "Hello, Milky Way!\n"

Hello/World.pm

# "package" is the namespace where the module's functionality/data resides. # It dictates the name of the file if you want it to be "use"d.# If more than one word, it constrains the location of the module.packageHello::World;# By default Perl allows you to use variables without declaring # them.  This may be convenient for short scripts and one-liners.# But in a longer unit of code such as a module it is wise to declare # your variables both to catch typos and to constrain their # accessibility appropriately from outside the module. The strict pragma# forces you to declare your variables.usestrict;# Similarly, Perl does not issue most compiler or run-time warnings by default.# More complicated scripts, such as most modules, will usually find them very # helpful for debugging. The warnings pragma turns on optional warnings.usewarnings;# 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.00';# Inherit from the "Exporter" module which handles exporting functions.# Most procedural modules make use of this.usebase'Exporter';# When the module is invoked, export, by default, the function "hello" into # the namespace of the using code.our@EXPORT=qw(hello);# 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 NAMEHello::World - An encapsulation of a common output message=head1 SYNOPSIS  use Hello::World;  print hello();  print hello("Milky Way");=head1 DESCRIPTIONThis is a procedural module which gives you the famous "Hello, world!"message, and it’s even customizable!=head2 FunctionsThe following functions are exported by default=head3 hello    print hello();    print hello($target);Returns the famous greeting.  If a C<$target> is given it will be used,otherwise "world" is the target of your greeting.=cut# define the function hello().subhello{my$target=shift;$target='world'unlessdefined$target;return"Hello, $target!\n";}=head1 AUTHORJoe Hacker <joe@joehacker.org>=cut# A Perl module must end with a true value or else it is considered not to# have loaded.  By convention this value is usually 1 though it can be# any true value.  A module can end with false to indicate failure but# this is rarely used and it would instead die() (exit with an error).1;

Since Hello/World.pm is not in your @INC path, you must specify . on the command line to run the above example:

perl -I. hello_world.pl

Object-oriented example

Here's an example of the same thing done in an object-oriented style. The advantage of an OO module is that each object can be configured independently from other objects.

hello_world.pl

#!/usr/bin/perluseHello::World;my$hello=Hello::World->new;$hello->print;# prints "Hello, world!\n"$hello->target("Milky Way");$hello->print;# prints "Hello, Milky Way!\n"my$greeting=Hello::World->new(target=>"Pittsburgh");$greeting->print;# prints "Hello, Pittsburgh!\n"$hello->print;# still prints "Hello, Milky Way!\n"

Hello/World.pm

# In Perl there is no special 'class' definition.  A namespace is a class.packageHello::World;usestrict;usewarnings;our$VERSION="1.00";=head1 NAMEHello::World - An encapsulation of a common output message=head1 SYNOPSIS    use Hello::World;    my $hello = Hello::World->new();    $hello->print;=head1 DESCRIPTIONThis is an object-oriented library which can print the famous "H.W."message.=head2 Methods=head3 new    my $hello = Hello::World->new();    my $hello = Hello::World->new( target => $target );Instantiates an object which holds a greeting message.  If a C<$target> isgiven it is passed to C<< $hello->target >>.=cut# The constructor of an object is called new() by convention.  Any# method may construct an object and you can have as many as you like.subnew{my($class,%args)=@_;my$self=bless({},$class);my$target=exists$args{target}?$args{target}:"world";$self->{target}=$target;return$self;}=head3 target    my $target = $hello->target;    $hello->target($target);Gets and sets the current target of our message.=cutsubtarget{my$self=shift;if(@_){my$target=shift;$self->{target}=$target;}return$self->{target};}=head3 to_string    my $greeting = $hello->to_string;Returns the $greeting as a string=cutsubto_string{my$self=shift;return"Hello, $self->{target}!";}=head3 print    $hello->print;Outputs the greeting to STDOUT=cutsubprint{my$self=shift;print$self->to_string(),"\n";}=head1 AUTHORJoe Hacker <joe@joehacker.org>=cut1;

Perl packages and namespaces

A running Perl program has a built-in namespace called "main", which is the default name. For example, a subroutine called Sub1 can be called as Sub1() or main::Sub1(). With a variable the appropriate sigil is placed in front of the namespace; so a scalar variable called $var1 can also be referred to as $main::var1, or even $::var1. Other namespaces can be created at any time.

packageNamespace1;$var1=1;# created in namespace Namespace1, which is also created if not pre-existingour$var2=2;# also created in that namespace; our required if use strict is appliedmy$var3=3;# lexically-scoped my-declared - NOT in any namespace, not even main
$Namespace2::var1=10;# created in namespace Namespace2, also created if not pre-existingour$Namespace2::var2=20;# also created in that namespacemy$Namespace2::var3=30;#compilation error:my-declared variables CAN'T belong to a package

Package declarations apply package scope till the next package declaration or the end of the block in which the declaration is made.

our$mainVar='a';packageSp1;our$sp1aVar='aa';print"$main::mainVar\t$sp1aVar\n";# note mainVar needs qualifyingpackageSp2;our$sp2aVar='aaa';print"$main::mainVar\t$Sp1::sp1aVar\t$sp2aVar\n";# note mainVar and sp1aVar need qualifyingpackagemain;print"$mainVar\t$Sp1::sp1aVar\t$Sp2::sp2aVar\n";# note sp1aVar and sp2aVar need qualifying$mainVar='b';{# NOTE previously created packages and package variables still accessiblepackageSp1;our$sp1bVar='bb';print"$main::mainVar\t$sp1aVar\t$sp1bVar\n";# note mainVar needs qualifying{packageSp2;our$sp2bVar='bbb';print"$main::mainVar\t$Sp1::sp1aVar$Sp1::sp1bVar\t$sp2aVar$sp2bVar\n";}# note mainVar and sp1...Var need qualifyingprint"$main::mainVar\t$sp1bVar$sp1aVar\t$Sp2::sp2bVar$Sp2::sp2aVar\n";}# note package Sp1 applies by default# main applies again by default; all package variables still accessible as long as qualifiedprint"$mainVar\t$Sp1::sp1aVar$Sp2::sp2bVar\n";

Packages and modules

Conventionally, namespaces are associated with modules; in practice, there is usually one namespace per module and vice versa, but that's not mandated by the language. For example, the 'standard' module CGI.pm has the following declaration at its top:

packageCGI;

This module, and its functionality, would commonly be invoked as follows:

useCGI(':standard');# imports many functions, including b()...printb('Hello, world');# outputs <b>Hello, world</b>

A 'missing' subroutine could be added from the using program's namespace.

subCGI::bi {# define target namespace (CGI) and sub name (bi)returnb(i($_[0]));}

and invoked as below:

printCGI::bi('Hello, world');# outputs <b><i>Hello, world</i></b>

However, though technically feasible, that would be dubious programming practice. You might just as well define the sub in the calling namespace, and call it from that namespace.

Further reading

Related Research Articles

In computing, Common Gateway Interface (CGI) is an interface specification for web servers to execute programs that execute like console applications running on a server that generates web pages dynamically. Such programs are known as CGI scripts or simply as CGIs. The specifics of how the script is executed by the server are determined by the server. In the common case, a CGI script executes at the time a request is made and generates HTML.

"Hello, World!" program Traditional beginners computer program

A "Hello, World!" program generally is a computer program that outputs or displays the message "Hello, World!". Such a program is very simple in most programming languages, and is often used to illustrate the basic syntax of a programming language. It is often the first program written by people learning to code.

Perl Interpreted programming language

Perl is a family of two high-level, general-purpose, interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it also referred to its redesigned "sister language", Perl 6, before the latter's name was officially changed to Raku in October 2019.

In computer programming, the scope of a name binding—an association of a name to an entity, such as a variable—is the region of a computer program where the binding is valid: where the name can be used to refer to the entity. Such a region is referred to as a scope block. In other parts of the program the name may refer to a different entity, or to nothing at all.

Visual Basic .NET object-oriented computer programming language

Visual Basic .NET (VB.NET) is a multi-paradigm, object-oriented programming language, implemented on the .NET Framework. Microsoft launched VB.NET in 2002 as the successor to its original Visual Basic language. Although the ".NET" portion of the name was dropped in 2005, this article uses "Visual Basic [.NET]" to refer to all Visual Basic languages released since 2002, in order to distinguish between them and the classic Visual Basic. Along with Visual C#, it is one of the two main languages targeting the .NET framework.

In computer science, a dispatch table is a table of pointers to functions or methods. Use of such a table is a common technique when implementing late binding in object-oriented programming.

Originally, a one-liner program was textual input to the command-line of an operating system shell that performs some function in just one line of input. The one-liner can be

Raku (programming language) programming language derived from Perl

Raku is a member of the Perl family of programming languages. Formerly known as Perl 6, it was renamed in October 2019. Raku introduces elements of many modern and historical languages. Compatibility with Perl was not a goal, though a compatibility mode is part of the specification. The design process for Raku began in 2000.

In the Perl programming language, autovivification is the automatic creation of new arrays and hashes as required every time an undefined value is dereferenced. Perl autovivification allows a programmer to refer to a structured variable, and arbitrary sub-elements of that structured variable, without expressly declaring the existence of the variable and its complete structure beforehand.

CGI.pm is a large and widely used Perl module for programming Common Gateway Interface (CGI) web applications, providing a consistent API for receiving and processing user input. There are also functions for producing HTML or XHTML output, but these are now unmaintained and are to be avoided. CGI.pm was a core Perl module but has been removed as of v5.22 of Perl. The module was written by Lincoln Stein and is now maintained by Lee Johnson.

In computer programming, an entry point is where the first instructions of a program are executed, and where the program has access to command line arguments.

The basic control structures of Perl are similar to those used in C and Java, but they have been extended in several ways.

String functions are used in computer programming languages to manipulate a string or query information about a string.

The syntax of JavaScript is the set of rules that define a correctly structured JavaScript program.

Oxygene (programming language) Object Pascal-based programming language

Oxygene is a programming language developed by RemObjects Software for Microsoft's Common Language Infrastructure, the Java Platform and Cocoa. Oxygene based on Delphi's Object Pascal, but also has influences from C#, Eiffel, Java, F# and other languages.

Zend Framework (ZF) is an open source, object-oriented web application framework implemented in PHP 7 and licensed under the New BSD License. The framework is basically a collection of professional PHP-based packages. The framework uses various packages by the use of Composer as part of its package dependency managers; some of them are PHPUnit for testing all packages, Travis CI for continuous Integration Services. Zend Framework provides to users a support of the Model View Controller (MVC) in combination with Front Controller solution. MVC implementation in Zend Framework has five main areas. The router and dispatcher functions to decide which controller to run based on data from URL, and controller functions in combination with the model and view to develop and create the final web page.

Plack (software) web application framework

Plack is a Perl web application programming framework inspired by Rack for Ruby and WSGI for Python, and it is the project behind the PSGI specification used by other frameworks such as Catalyst and Dancer. Plack allows for testing of Perl web applications without a live web server.

The Perl virtual machine is a stack-based process virtual machine implemented as an opcodes interpreter which runs previously compiled programs written in the Perl language. The opcodes interpreter is a part of the Perl interpreter, which also contains a compiler in one executable file, commonly /usr/bin/perl on various Unix-like systems or perl.exe on Microsoft Windows systems.

The structure of the Perl programming language encompasses both the syntactical rules of the language and the general ways in which programs are organized. Perl's design philosophy is expressed in the commonly cited motto "there's more than one way to do it". As a multi-paradigm, dynamically typed language, Perl allows a great degree of flexibility in program design. Perl also encourages modularization; this has been attributed to the component-based design structure of its Unix roots, and is responsible for the size of the CPAN archive, a community-maintained repository of more than 100,000 modules.

In software engineering, the module pattern is a design pattern used to implement the concept of software modules, defined by modular programming, in a programming language with incomplete direct support for the concept.