Perl module

from Wikipedia, the free encyclopedia
Mechanism for integrating and using Perl modules

A Perl module is a separate component of a computer program written in Perl .

A module has its source code in a module file with the extension .pm, which in turn contains a package, i.e. its own namespace (although this is not absolutely necessary); the structure of the package name (and thus the namespace name) reflects the file system (so that the Net :: FTP module is in the file Net/FTP.pm). In addition, a Perl module with a namespace should be used as a class if object-oriented programming is used (in Perl, namespaces are equivalent to classes, but do not have to be used as such).

A collection of modules with associated documentation, build scripts, etc. form a distribution . The Perl community maintains a large collection of packages etc. on CPAN .

Perl as a programming language allows a variety of programming styles. You can find both a module that is procedurally (“conventional”, similar to C ) written (e.g. Test-Simple ) and modules with object-oriented interfaces (e.g. XML :: Parser ), and both that one as well as the other can perform their tasks efficiently, since it may a. It depends on the context: In connection with XML , an object-oriented module interface is much more useful than e.g. B. with a mathematical function library. Modules can also be used as mixin methods or be a pragma (e.g. strict ), which then has an immediate effect on the program. Modules can also be used to change the syntax of the language itself. Modules usually only have an effect on the visibility area in which they were loaded (usually a file).

It is common to Perl modules to have embedded documentation as plain old documentation . POD is flexible enough to write articles, websites or even books (e.g. Programming Perl ), unlike javadoc , which specializes in documenting classes. The documentation usually follows the structure of a manpage .

The code on this page is based on Perl 5.10.0 and should therefore also work with Perl> 5.10.0. In particular, the namespace examples cannot be executed with Perl 5.6. The use of the pragma is strictassumed (exceptions are marked) , which results in cleaner code.

Examples

A "Hello World function" can be implemented in various ways with modules, whereby it is not mandatory packageto pack the function in a module (in Perl more like a namespace; ) (in contrast to Java ); rather, a function can be defined and used anywhere (in modules also via integration use). Nevertheless, for reasons of clarity, it is common to put the elements of a Perl module in a namespace ( package). A Hello World function would look like this:

package module1;
sub hello(){ print "Hello, World!\n"; }

Procedural approach

In hello.pm the function is hello()defined and implemented, in the main script main.pl runs.

main.pl :

#!/usr/bin/perl -w
use strict;  # Pragma strict wird genutzt, sodass eine besonders strenge Prüfung durchgeführt wird
use world::hello;   # hello.pm world/hello.pm, wobei die Basis-Verzeichnisse, also die Verzeichnis, in denen
                    # world/ liegen könnte, in einer Pfadvariable namens @INC angegeben sind, die auch das
                    # aktuelle Verzeichnis enthält

# entweder
hello::hallo();
# oder
hello->hallo("Erde");

hello.pm :

package hello;

# Zeilen mit einem "=" kennzeichnen integrierte PO-Dokumentation.
# Ein POD-Abschnitt endet mit "=cut" und kann an beliebiger Stelle stehen.

=head1 NAME
Hello:World -- DIE Hello-World-Implementierung.

=head1 ZUSAMMENFASSUNG

use Hello::World;
hallo();
hallo("Erde");

=head2 Funktionen

Folgende Funktionen stehen zur Verfügung:

=head3 hallo()

hallo()
hallo($etw_anderes)

=head1 Autor

Otto Normalhacker <otto@normalo.de>

=cut

sub hallo(;$)
{
    my $etw_anderes = shift @_;
    defined $etw_anderes ? print "Hello $etw_anderes !\n" : print "Hello world!\n";
}

return 1; # Jedes Perl-Modul muss einen wahren Wert an den Compiler liefern, sonst gibt es einen Error

Object-oriented approach

Object-oriented solutions require more code in all languages ​​and are less efficient in execution. During development, however, object orientation is often more efficient than a procedural solution. In Perl, object orientation is implemented through references (scalars with a memory address) to code and a hash.

main.pl :

#!/usr/bin/perl -w
use strict;
use Hello::World; # Modul liegt in Hello/World.pm

my $hello = new Hello::World; # Objekt erzeugen

$hello->gib_begr_aus; # "Hello world" ausgeben

$hello = $hello->aendere_ding("galaxis"); # Zu begrüßendes Objekt in "Galaxis" ändern und das geänderte Objekt zurückspeichern

my $begr = $hello->begr_in_string; # Begrüßung speichern...

print $begr; # und ausgeben

World.pm :

package Hello::World; # Im objektorientierten Ansatz muss der Namensraum definiert sein, da in Perl jede Klasse ein Namensraum ist

use strict;
use warnings;

#
# Eventuelle
# POD-Inhalte
#

sub new($$) # Prototyp des Konstruktors
{
    my $class = shift @_;
    if ( exists $_[0] ) # Falls nicht anders angegeben, begrüße "world"
    {
         my $ding = $_[0];
    } else
    {
         my $ding = "world";
    }
    my $self = { ding => $ding }; # Hash-Referenz mit Daten wird erzeugt...
    bless($self, $class);  # ... mit dem Klassennamen "abgesegnet"...
    return $self; # ...und zurückgegeben
}

sub aendere_ding($$) # Das Ding ändern, das begrüßt wird
{
    my $self = shift @_; # Objekt annehmen
    my $ding = shift @_;
    $self->{ding} = $ding; # Daten manipulieren...
    return $self; # ...geändertes Objekt zurückgeben
}

sub gib_begr_aus($) # Die erzeugte Begrüßung auf STDOUT ausgeben
{
        my $self = shift @_; # Objekt wird wieder angenommen...
        print("Hello $self->{ding}!\n"); # ...und ausgegeben.
}

sub begr_in_string($) # Die erzeugte Begrüßung als String zurückgeben, z.&nbsp;B. bei Verwendung mit print()
{
        my $self = shift @_;
        return "Hello $self->{ding}!\n";
}

Namespaces and areas of application

Unless otherwise declared, a Perl program has the namespace at runtime main- a function func1()can be called both func1()as and as main::func1(); the value of $varcan be found out both via $varand with $main::var. New namespaces can be declared and used at any time. Variables that have been mydeclared with have no namespace affiliation and exist globally, but only within a file. Variables that are also ourdeclared have a namespace affiliation and exist completely globally, i.e. also across file limits, although they are in a different file than the one with the declaration (i.e. the integrating file) with the scope resolution operator :: and the namespace have to be called. In one and the same file, a our variable from a foreign namespace only needs to be called fully qualified (with :: and namespace) if a our or my variable with the same name already exists in the calling namespace.

package namensraum1;
my $var = "foo"; # mit my deklarierte Variablen liegen in keinem Namensraum.
                 # Ein Rufen mittels $namensraum1::var hat keinen Erfolg, mit $var jedoch überall.
our $var2 = "bar"; # our deklariert eine an den Namensraum gebundene Variable (our ist nur nötig mit strict)

$namensraum2::var3 = 42; # Namensraum existiert noch nicht, wird dabei aber gleich erstellt. (nur, falls strict nicht genutzt wird)
our $namensraum2::var4 = 21; # Mit und ohne strict: Fehler
my $namensraum2::var5 = 23.11; # Fehler, da my nicht namensraumgebunden ist

sub namensraum2::hello_w() { print("Hello World!\n"); } # Geht sowohl mit als auch ohne strict

See also

Web links