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 <[email protected]>

=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 <[email protected]>
 
=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:

Adam BackLahirJuli 1970 (umur 53)London, InggrisPendidikanUniversity of ExeterKarier ilmiahBidang Protokol kriptografi Mata uang digital Privacy-enhancing technologies Komputasi terdistribusi InstitusiZero-Knowledge SystemsPi CorporationBlockstreamDisertasiParallelization of general purpose programs using optimistic techniques from parallel discrete event simulation (1995)Pembimbing doktoralStephen Turner Situs webcypherspace.org/adamAdam Back (Lahir bulan Juli 1970) adalah ah...

 

Criminal MindsPoster promosiJudul asli크리미널 마인드 GenreProseduralLagaBerdasarkanCriminal Mindsoleh Jeff DavisPengembangStudio DragonDitulis olehHong Seung-HyunAndrew S. Wilder (original)Bo Crese (original)SutradaraYang Yoon-hoLee Jung-hyo (resigned)[1][2]PemeranLee Joon-giSon Hyun-jooMoon Chae-wonYoo SunLee Sun-binGo YoonKim Yeong-cheolNegara asalKorea SelatanBahasa asliKoreaJmlh. episode20ProduksiProduser eksekutifJung Tae-wonPengaturan kameraSingle-cameraDurasi60...

 

Pour les articles homonymes, voir Beausoleil. Beausoleil Le clocher de l'église Saint-Joseph. Blason Administration Pays France Région Provence-Alpes-Côte d’Azur Département Alpes-Maritimes Arrondissement Nice Intercommunalité Communauté d'agglomération de la Riviera française Maire Mandat Gérard Spinelli 2020-2026 Code postal 06240 Code commune 06012 Démographie Gentilé Beausoleillois Populationmunicipale 12 674 hab. (2021 ) Densité 4 543 hab./km2 Populatio...

Part of a series onBritish law Acts of Parliament of the United Kingdom Year      1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 ...

 

Machine used for studying the effects of air moving around objects NASA wind tunnel with the scale model of the MD-11 wide-body airliner 16-foot supersonic wind tunnel at Arnold Air Force Base, 1960 A model Cessna with helium-filled bubbles showing pathlines of the wingtip vortices Wind tunnels are machines where an object is held stationary inside a tube, and air is blown around it to study the interaction between the object and the moving air. They are used to test the aerodynamic effects o...

 

Japanese dive bomber and training aircraft D3Y Myojo Role TrainerDive bomberType of aircraft Manufacturer Yokosuka First flight 1945 Status Cancelled Primary user IJN Navy Air Service (Intended) Produced 1945 Number built 2 Prototypes3 Production Developed from Aichi D3A The Yokosuka D3Y Myojo (明星, Venus) was a Japanese two-seat dive bomber/trainer designed and built by the Yokosuka Naval Air Technical Arsenal. Derived from the Aichi D3A, it was made nearly entirely of wood in an att...

Nassira El MoaddemFonctionRédactrice en chefBondy Blogseptembre 2016 - décembre 2018Ilyes Ramdani (d)BiographieNaissance 23 juin 1984 (39 ans)Romorantin-LanthenayNationalités françaisemarocaineFormation Lycée Claude de France de Romorantin-Lanthenay (jusqu'en 2002)Université de Tours (2002-2003)Institut d'études politiques de Grenoble (septembre 2003 - 2007)Institut national des langues et civilisations orientales (2008-2010)École supérieure de journalisme de Lille (2010-2012)Ac...

 

Questa voce sull'argomento centri abitati della Virginia è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. Lexingtoncittà indipendente(EN) Lexington city, Virginia Lexington – Veduta LocalizzazioneStato Stati Uniti Stato federato Virginia ConteaNon presente AmministrazioneSindacoMimi Elrod TerritorioCoordinate37°47′02.48″N 79°26′34.14″W / 37.784021°N 79.442816°W37....

 

Online gambling company DafabetAvailable inMultilingualFounded2004Area servedAsia Pacific region / EuropeIndustryOnline gamblingServicesOnline betting and gamingEmployees1000+URLOfficial website Dafabet is an online betting site. The company was founded on 7 November 2004 and is headquartered in Makati, Philippines. History This section needs additional citations for verification. Please help improve this article by adding citations to reliable sources in this section. Unsourced...

この項目には、一部のコンピュータや閲覧ソフトで表示できない文字が含まれています(詳細)。 数字の大字(だいじ)は、漢数字の一種。通常用いる単純な字形の漢数字(小字)の代わりに同じ音の別の漢字を用いるものである。 概要 壱万円日本銀行券(「壱」が大字) 弐千円日本銀行券(「弐」が大字) 漢数字には「一」「二」「三」と続く小字と、「壱」「�...

 

2006 888.com World Snooker ChampionshipTournament informationDates15 April – 1 May 2006 (2006-04-15 – 2006-05-01)VenueCrucible TheatreCitySheffieldCountryEnglandOrganisationWPBSAFormatRanking eventTotal prize fund£896,240Winner's share£200,000Highest break Ronnie O'Sullivan (ENG) (140)FinalChampion Graeme Dott (SCO)Runner-up Peter Ebdon (ENG)Score18–14← 2005 2007 → Snooker tournament The 2006 World Snooker Champi...

 

Indian television series ItihaasGenreDramaCreated byNirmala SoodDeveloped byBalaji TelefilmsWritten byStoryEkta Kapoor Vinod Ranganath Screenplay Vinod Ranganath Dialogues B. R. IsharaDirected byGogi AnandCreative directorMonisha SinghStarringsee belowTheme music composerNawab ArzooComposerLalit SenCountry of originIndiaOriginal languageHindiNo. of seasons1No. of episodes488ProductionProducersEkta KapoorShobha KapoorProduction locationsMumbai, Maharashtra, IndiaEditorsDharmesh Shah Dheerendra...

Flag of English historic county CumberlandProportion3:5Adopted13 December 2012 The Cumberland flag at Beacon Edge, Penrith The Cumberland flag is the flag of the historic county of Cumberland. It was registered with the Flag Institute as the flag of the county in December 2012.[1] Design The flag is based on the pattern of the arms of the former Cumberland County Council, originally granted by the College of Arms on 19 September 1950,[2] namely: Per fesse vert and barry wavy o...

 

اختبار السمع من أنواع اختبار طبي[1]  ن.ف.م.ط. D006320 تعديل مصدري - تعديل   يوفر اختبار السمع تقييماً لمدى إحساس الشخص بالسمع، وغالبًا ما يتم إجراؤه من قبل أخصائي السمع باستخدام مقياس السمع. يستخدم مقياس السمع لتحديد مدى حساسية السمع على نطاق ترددات مختلفة. هناك اختبارا�...

 

Uva

Disambiguazione – Se stai cercando altri significati, vedi Uva (disambigua). Disambiguazione – Acino rimanda qui. Se stai cercando altri significati, vedi Acino (disambigua). Uva L'uva è il frutto della vite (Vitis vinifera) e di altre specie o ibridi del genere Vitis. Indice 1 Botanica 2 Utilizzo 3 Proprietà di uva e derivati 4 Produzione 5 Note 6 Voci correlate 7 Altri progetti 8 Collegamenti esterni Botanica Schema della struttura di un grappolo d'uva Il grappolo d'uva è un...

American party leadership vote 2009 Republican National Committee chairmanship election ← 2007 January 20, 2009 (2009-01-20) 2011 → 168 members of the Republican National Committee85 votes needed to win   Candidate Michael Steele Katon Dawson First round 46 votes27.4% 28 votes16.7% Sixth round 91 votes54.2% 77 votes45.8%   Candidate Mike Duncan Saul Anuzis First round 52 votes31.0% 22 votes13.1% Sixth round Withdrawn Withdrawn Chairman before ele...

 

Indian politician Ram Naik19th Governor of Uttar PradeshIn office22 July 2014 – 28 July 2019Chief MinisterAkhilesh YadavYogi AdityanathPreceded byAziz Qureshi (Acting)Succeeded byAnandiben PatelMember of Parliament, Lok SabhaIn office1989–2004Preceded byAnoopchand ShahSucceeded byGovinda AhujaConstituencyMumbai NorthMinister of RailwaysIn office6 August 1999 (1999-08-06) – 12 October 1999 (1999-10-12)Prime MinisterAtal Bihari VajpayeeP...

 

Fictional character from the Terminator franchise Fictional character Miles DysonTerminator characterJoe Morton as Miles Dyson in Terminator 2: Judgment Day (1991)First appearanceTerminator 2: Judgment Day (1991)Last appearanceTerminator Genisys (2015)Created byJames CameronWilliam Wisher Jr.Portrayed by Joe Morton (T2) Phil Morris (The Sarah Connor Chronicles) Courtney B. Vance (Genisys) In-universe informationSpeciesHumanGenderMaleTitleDoctorOccupationScientistSpouseTarissa DysonChildrenDan...

François HollandeHollande pada tahun 2017 Presiden Prancis ke-24Masa jabatan15 Mei 2012 – 14 Mei 2017Perdana MenteriJean-Marc AyraultPendahuluNicolas SarkozyPenggantiEmmanuel MacronPangeran AndorraMasa jabatan15 Mei 2012 – 14 Mei 2017Menjabat bersama Joan Enric Vives SicíliaPerdana MenteriAntoni MartíPerwakilanChristian FrémontPendahuluNicolas SarkozyPenggantiEmmanuel MarconPresiden Dewan Umum CorrèzeMasa jabatan20 Maret 2008 – 15 Mei 2012Pendahul...

 

Cihan ÇanakNazionalità Turchia Belgio Altezza175 cm Peso65 kg Calcio RuoloCentrocampista Squadra Trabzonspor CarrieraGiovanili 2012-2021 Standard Liegi Squadre di club1 2021-2024 Standard Liegi67 (1)2022-2023 SL165 (0)2024- Trabzonspor0 (0) Nazionale 2020 Belgio U-152 (1)2022 Belgio U-178 (0)2023 Belgio U-193 (0)2022 Belgio U-201 (0)2023- Turchia U-218 (2) 1 I due numeri indicano le presenze e le reti segnate, per le sole partite di campionato.Il simbolo �...