Perl-модуль

Модуль Perl — это отдельный компонент программного обеспечения для Perl языка программирования . Технически это особый набор соглашений по использованию механизма пакетов Perl , который стал общепринятым. [ обсуждать ]
Модуль определяет, что его исходный код находится в пакете (очень похоже на пакет Java ), механизм Perl для определения пространств имен , например CGI или Net::FTP или XML::Parser ; структура файла отражает структуру пространства имен (например, исходный код Net::FTP находится в Net/FTP.pm ). Более того, модуль является Perl-эквивалентом класса при использовании -ориентированного программирования . объектно [ обсуждать ]
Набор модулей с сопроводительной документацией , сценариями сборки и обычно набором тестов составляет дистрибутив . Сообщество Perl располагает значительной библиотекой дистрибутивов, доступных для поиска и загрузки через CPAN .
Perl — это язык, допускающий множество различных стилей программирования. Разработчик с такой же вероятностью найдет модуль, написанный как в процедурном стиле (например, Test::Simple ), так и в объектно-ориентированном стиле (например, XML::Parser ), оба считаются одинаково допустимыми в зависимости от того, что модуль должен делать. Модули также могут использоваться для смешивания методов ( DBIx::Class ) или быть прагмой ( strict.pm ), которая оказывает эффект сразу после загрузки. Модули можно использовать даже для изменения синтаксиса языка. Эффект модулей Perl обычно ограничивается текущей областью , в которой они были загружены.
Модули Perl обычно имеют встроенную документацию в формате Perl Plain Old Documentation . POD мало навязывает автору структуры. Он достаточно гибок, чтобы его можно было использовать для написания статей, веб-страниц и даже целых книг, таких как «Программирование на Perl» . Сравните с javadoc , который специализируется на документировании классов Java . По соглашению, документация модуля обычно соответствует структуре man-страницы Unix .
Язык Perl определяется единственной реализацией (называемой «perl») и добавляется (а в редких случаях удаляется) к каждой новой версии. По этой причине автору модуля важно знать, какие функции он использует и какова минимальная необходимая версия Perl. Для кода на этой странице требуется Perl 5.6.0, который сейчас считается довольно старым.
Примеры
[ редактировать ]Ниже приведены примеры « Hello, World », реализованные в различных стилях модулей. Необходимо понимать, что в Perl модуль не обязателен; функции и код можно определять и использовать где угодно. Это просто для примера. Сравните с Java , где класс всегда необходим. Настоящая функция «Hello, World» могла бы быть написана так:
sub hello { "Hello, world!\n" }
print hello();
или просто напечатать в одну строку:
print "Hello, world!\n";
Процедурный пример
[ редактировать ]Вот «Hello, World», реализованный как процедурный модуль с настраиваемой целью приветствия, просто для интереса. Также включен короткий сценарий, иллюстрирующий использование модуля.
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"
Привет/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;
Поскольку Hello/World.pm не находится в вашем пути @INC, вам необходимо указать . в командной строке, чтобы запустить приведенный выше пример:
перл -I. hello_world.pl
Объектно-ориентированный пример
[ редактировать ]Вот пример того же самого, сделанного в объектно-ориентированном стиль. Преимущество ОО-модуля в том, что каждый объект можно настроить независимо от других объектов.
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"
Привет/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 и пространства имен
[ редактировать ]Запущенная программа Perl имеет встроенное пространство имен, называемое « main
", которое является именем по умолчанию. Например, подпрограмма с именем Sub1
можно назвать как Sub1()
или main::Sub1()
. При использовании переменной соответствующий символ помещается перед пространством имен; поэтому скалярная переменная, называемая $var1
также можно назвать $main::var1
или даже $::var1
. Другие пространства имен могут быть созданы в любое время.
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
Объявления пакета применяют область действия пакета до следующего объявления пакета или до конца блока, в котором сделано объявление.
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";
Пакеты и модули
[ редактировать ]Традиционно пространства имен связаны с модулями; на практике обычно на каждый модуль приходится одно пространство имен, и наоборот, но это не предусмотрено языком. Например, «стандартный» модуль CGI.pm имеет в верхней части следующее объявление:
package CGI;
Этот модуль и его функциональность обычно вызываются следующим образом:
use CGI (':standard'); # imports many functions, including b()
...
print b('Hello, world'); # outputs <b>Hello, world</b>
«Отсутствующую» подпрограмму можно добавить из пространства имен используемой программы.
sub CGI::bi { # define target namespace (CGI) and sub name (bi)
return b(i($_[0]));
}
и вызывается, как показано ниже:
print CGI::bi('Hello, world'); # outputs <b><i>Hello, world</i></b>
Однако, хотя это технически осуществимо, это было бы сомнительной практикой программирования. С таким же успехом вы можете определить подпрограмму в вызывающем пространстве имен и вызывать ее из этого пространства имен.