Perl module

Diagram of the mechanism of using perl modules.

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]

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:

sub hello { "Hello, world!\n" }
print hello();

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.
use Hello::World;

print hello();             # prints "Hello, world!\n"
print hello("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.

package Hello::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.
 
use strict;
 
# 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.
 
use warnings;
 
# 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.

use base '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 NAME

Hello::World - An encapsulation of a common output message

=head1 SYNOPSIS

  use Hello::World;
  print hello();
  print hello("Milky Way");

=head1 DESCRIPTION

This is a procedural module which gives you the famous "Hello, world!"
message, and it’s even customizable!

=head2 Functions

The 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().

sub hello {
    my $target = shift;
    $target = 'world' unless defined $target;
    
    return "Hello, $target!\n";
}

=head1 AUTHOR

Joe 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/perl

use Hello::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.
package Hello::World;

use strict;
use warnings;
 
our $VERSION = "1.00";

=head1 NAME
 
Hello::World - An encapsulation of a common output message
 
=head1 SYNOPSIS
 
    use Hello::World;
    my $hello = Hello::World->new();
    $hello->print;
 
=head1 DESCRIPTION
 
This 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> is
given 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.
 
sub new {
    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.
 
=cut
 
sub target {
    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
 
=cut
 
sub to_string {
    my $self = shift;
    return "Hello, $self->{target}!";
}
 
 
=head3 print
 
    $hello->print;
 
Outputs the greeting to STDOUT
 
=cut
 
sub print {
    my $self = shift;
    print $self->to_string(), "\n";
}
 
=head1 AUTHOR
 
Joe Hacker <joe@joehacker.org>
 
=cut
 
1;

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.

package Namespace1;
$var1 = 1;	# created in namespace Namespace1, which is also created if not pre-existing
our $var2 = 2;	# also created in that namespace; our required if use strict is applied
my $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-existing
our $Namespace2::var2 = 20; # also created in that namespace
my $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';
package Sp1;
our $sp1aVar = 'aa';
print "$main::mainVar\t$sp1aVar\n"; # note mainVar needs qualifying
package Sp2;
our $sp2aVar = 'aaa';
print "$main::mainVar\t$Sp1::sp1aVar\t$sp2aVar\n";# note mainVar and sp1aVar need qualifying
package main;
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 accessible
    package Sp1;
    our $sp1bVar = 'bb';
    print "$main::mainVar\t$sp1aVar\t$sp1bVar\n"; # note mainVar needs qualifying
    {
        package Sp2;
        our $sp2bVar = 'bbb';
        print "$main::mainVar\t$Sp1::sp1aVar$Sp1::sp1bVar\t$sp2aVar$sp2bVar\n";
    }		# note mainVar and sp1...Var need qualifying
    print "$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 qualified
print "$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:

package CGI;

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

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

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

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

and invoked as below:

print CGI::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

Read other articles:

Jepang Artikel ini adalah bagian dari seri Politik dan KetatanegaraanJepang Konstitusi Konstitusi Jepang Sejarah Hukum Monarki Kaisar (daftar) Akihito Putra Mahkota Naruhito Istana Kaisar Badan Rumah Tangga Kekaisaran Badan legislatif Parlemen Jepang Dewan Perwakilan Rakyat Ketua Tadamori Ōshima Wakil Ketua Hirotaka Akamatsu Majelis Tinggi Presiden Chuichi Date Wakil Presiden Akira Gunji Pemimpin Oposisi Yukio Edano Eksekutif Perdana Menteri (daftar) Shinzō Abe Wakil Perdana Menteri Tarō A...

 

The ActGenre Kasus nyata Drama Antologi Pembuat Nick Antosca Michelle Dean Pemeran Patricia Arquette Joey King AnnaSophia Robb Chloë Sevigny Calum Worthy Penata musikJeff RussoNegara asalAmerika SerikatBahasa asliInggrisJmlh. musim1Jmlh. episode8 (daftar episode)ProduksiProduser eksekutif Nick Antosca Michelle Dean Britton Rizzio Gregory Shephard ProduserJan Peter MeyboomDurasi48–60 menitRumah produksi Eat the Cat Writ Large Universal Content Productions RilisJaringan asliHuluRilis a...

 

Resolutie 1227 Van de Veiligheidsraad van de Verenigde Naties Datum 10 februari 1999 Nr. vergadering 3975 Code S/RES/1227 Stemming voor15onth.0tegen0 Onderwerp Eritrees-Ethiopische Oorlog Beslissing Eiste een einde aan de vijandelijkheden. Samenstelling VN-Veiligheidsraad in 1999 Permanente leden  China ·  Frankrijk ·  Rusland · Vlag van Verenigd Koninkrijk Verenigd Koninkrijk · Vlag van Verenigde Staten Verenigde Staten Niet-permanente leden  Argentinië

This article does not cite any sources. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: This Christmas TobyMac song – news · newspapers · books · scholar · JSTOR (April 2019) (Learn how and when to remove this template message) 2002 single by TobyMacThis ChristmasThis ChristmasSingle by TobyMacReleased2002Recorded2002Genre Christian hip hop rapcore Christian r...

 

Radio Free Europe dan Radio Liberty dialihkan ke halaman ini. Untuk lagu R.E.M., lihat Radio Free Europe (lagu). Untuk stasiun radio Britania UCKG, lihat Liberty Radio. Radio Free Europe/Radio LibertyLogo resmi RFE/RLKawasan penyiaran RFE/RL pada 2009SingkatanRFE/RLTanggal pendirian1949 (Radio Free Europe), 1953 (Radio Liberty), 1976 (bergabung)TipePerusahaan Sec 501(c)3 nirlaba swastaTujuanPenyiaran mediaKantor pusatPrague Broadcast CenterLokasiPrahaBahasa resmi Inggris; program tersedia dal...

 

Eames Molded Plastic & Fiberglass ArmchairThe Armchair, with central aluminium stand (DAL)DesignerCharles and Ray EamesDate1948-1950MaterialsZenaloy (polyester reinforced with fiberglass)Style / traditionMid-century modern furniture designSold byHerman Miller (United States)Vitra (Switzerland) The Eames Molded Plastic & Fiberglass Armchair is a fiberglass chair, designed by Charles and Ray Eames, that appeared on the market in 1950.[1] The chair was intentionally designed for ...

الكنيسة الأثيوبية الكاثوليكية رجل دين أثيوبي، بالزي التقليدي والصليب التقليدي.رجل دين أثيوبي، بالزي التقليدي والصليب التقليدي. الدين المسيحية العائلة الدينية الكنائس المسيحية الكاثوليكية الشرقية المؤسس المبشرون اللاتينيون تاريخ الظهور 1622. مَنشأ أثيوبيا. الأصل كنيسة ا...

 

Soviet aircraft machine gun This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (June 2013) (Learn how and when to remove this template message) ShKAS machine gun A ShKAS at the Zadorozhny Equipment MuseumTypeAircraft machine gunPlace of originSoviet UnionService historyUsed bySee UsersWars World War II Spanish Civil War Second Sino-Japanese War Pro...

 

2017 studio album by The Charm The FuryThe Sick, Dumb & HappyStudio album by The Charm The FuryReleased17 March 2017 (2017-03-17)Recorded2016StudioBackbone Audio (Amsterdam, Netherlands), ICP Studios (Brussels, Netherlands), Sandlane Studios (Rijen, Netherlands) and Sub-Bass Studios (Zwijndrecht, Netherlands)Genre Nu metal groove metal Length42:14LabelNuclear BlastProducerMathijs TiekenThe Charm The Fury chronology A Shade of My Former Self(2013) The Sick, Dumb &...

1944 Technicolor sports film directed by Clarence Brown National VelvetTheatrical release posterDirected byClarence BrownScreenplay byHelen DeutschBased onNational Velvet1935 novelby Enid BagnoldProduced byPandro S. BermanStarring Mickey Rooney Donald Crisp Elizabeth Taylor Angela Lansbury Anne Revere Reginald Owen Terry Kilburn CinematographyLeonard SmithEdited byRobert KernMusic byHerbert StothartProductioncompanyMetro-Goldwyn-MayerDistributed byLoew's, IncRelease dates December 14,...

 

American comic book artist and illustrator Steve EllisEllis at the 2011 New York Comic ConNationalityAmericanArea(s)Artist, InkerNotable worksHigh MoonThe SilencersCrimson DynamoAwardsHarvey Award, 2009Paper Screen Gem AwardGalerie d'art Yves Laroche: Street Camp Juried Show 2006Best in Show: Gen Con Art Show 2005http://www.hypersteve.com Steve Ellis is an American comic book artist and illustrator who has worked for Wizards of the Coast, DC Comics, Wildstorm, White Wolf, Moonstone Books and ...

 

Este artigo ou secção contém uma lista de referências no fim do texto, mas as suas fontes não são claras porque não são citadas no corpo do artigo, o que compromete a confiabilidade das informações. Ajude a melhorar este artigo inserindo citações no corpo do artigo. (Janeiro de 2021) Samário Promécio ← Samário → Európio -    62 Sm                                       &...

Japanese rock bandFlowFlow at Japan Expo 2012 in Paris, FranceBackground informationOriginJapanGenresAlternative rockpop punk[1]indie rockrap rock[2]Years active1998 (1998)–presentLabelsFun City Records (2002-2003)Ki/oon Music (2003–2020)Sacra Music (2020–present)MembersKōshi Asakawa (Vocal)Keigo Hayashi (Vocal)Takeshi Asakawa (Guitar)Kōtaro Gotō (Bass)Hiroshi Iwasaki (Drums)Websitewww.flow-official.jp Flow (stylized in all caps) is a Japanese rock band formed in...

 

Neolithic archaeological culture in the Pacific Known distribution of the Lapita culture Reconstruction of the face of a Lapita woman. National Museum of Ethnology (Japan) The Lapita culture is the name given to a Neolithic Austronesian people and their material culture, who settled Island Melanesia via a seaborne migration at around 1600 to 500 BCE.[1] They are believed to have originated from the northern Philippines, either directly, via the Mariana Islands, or both.[2] The...

 

Former video on demand service in the Philippines This article is about the service in the Philippines. For the U.K. service, see On Demand (Sky). Sky On DemandSky On Demand Final LogoType of siteVideo on demandAvailable inEnglishDissolvedSeptember 1, 2020; 3 years ago (2020-09-01)Successor(s)iWant TFCArea servedPhilippinesOwnerSky Cable CorporationURLArchived official website at the Wayback Machine (archived 2020-08-26)RegistrationSubscription to Sky Cable, Sk...

University in Ürümqi, Xinjiang Uyghur Autonomous Region, China Xinjiang Universityشىنجاڭ ئۇنىۋېرستېتى新疆大学TypePublicEstablished1924; 99 years ago (1924)Undergraduates> 20,000LocationÜrümqi, Xinjiang, China43°45′54″N 87°37′12″E / 43.7650°N 87.6201°E / 43.7650; 87.6201CampusUrbanWebsitewww.xju.edu.cn Xinjiang University (XJU; Uyghur: شىنجاڭ ئۇنىۋېرستېتى, Шинҗаң Университети;...

 

Bogumin redirects here. For the village in Poland, see Bogumin, Łódź Voivodeship. Town in Moravian-Silesian, Czech RepublicBohumínTownT. G. Masaryka Square and the town hall FlagCoat of armsBohumínLocation in the Czech RepublicCoordinates: 49°54′15″N 18°21′27″E / 49.90417°N 18.35750°E / 49.90417; 18.35750Country Czech RepublicRegionMoravian-SilesianDistrictKarvináFirst mentioned1256Government • MayorPetr Vícha (ČSSD)Area •...

 

استاد آل نهيانمعلومات عامةالمنطقة الإدارية أبو ظبي البلد  الإمارات العربية المتحدة التشييد والافتتاحالمقاول الرئيسي نادي الوحدة الإماراتي الاستعمالالرياضة كرة القدم المستضيف نادي الوحدة الإماراتي الإدارة نادي الوحدة الإماراتي معلومات أخرىالطاقة الاستيعابية 15٫894 ا...

Pop Jawa Volume 2Album studio karya Koes PlusDirilisAgustus 1974 (1974-08)[1]Genre Pop Jawa Durasi24:14LabelRemacoKronologi Koes Plus Volume 13(1974) Pop Jawa Volume 2(1974) Pop Melayu Volume 1(1974) Pop Jawa Volume 2 adalah album dari grup musik Koes Plus yang dirilis pada tahun 1974 di bawah label Remaco. Daftar lagu Sisi ANo.JudulPenciptaPenyanyiDurasi1.Thil Konthal KanthilTonnyTonny, Yok, Yon1:292.Rondo KatutYonYon2:113.Salah MongsoYokYok1:574.Padang BulanYonYonm2:305.Pak...

 

Eclissi solare dell'8 aprile 1652MappaTipoTotale Gamma0.7713 Magnitudine1.0412 Coordinate eclissi massima49.6°N 8.9°W Orari (UTC)Eclissi massima10:22:28 L'eclissi solare dell'8 aprile 1652 è un evento astronomico che ha avuto luogo il suddetto giorno attorno alle ore 10.22 UTC.[1] L'evento, di tipo totale, è stata visibile in alcune parti dell'Europa. L'eclissi ha avuto un'ampiezza massima di 213 km ed è durata 2 minuti e 49 secondi. Indice 1 Osservazioni documentate 2 Eclissi co...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!