Plan 9 from Bell Labs’s /usr/web/sources/contrib/gabidiaz/root/sys/man/1perl/perlmod

Copyright © 2021 Plan 9 Foundation.
Distributed under the MIT License.
Download the Plan 9 distribution.


.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings.  \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote.  | will give a
.\" real vertical bar.  \*(C+ will give a nicer C++.  Capital omega is used to
.\" do unbreakable dashes and therefore won't be available.  \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
.    ds -- \(*W-
.    ds PI pi
.    if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
.    if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\"  diablo 12 pitch
.    ds L" ""
.    ds R" ""
.    ds C` ""
.    ds C' ""
'br\}
.el\{\
.    ds -- \|\(em\|
.    ds PI \(*p
.    ds L" ``
.    ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD.  Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
.    de IX
.    tm Index:\\$1\t\\n%\t"\\$2"
..
.    nr % 0
.    rr F
.\}
.\"
.\" For nroff, turn off justification.  Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear.  Run.  Save yourself.  No user-serviceable parts.
.    \" fudge factors for nroff and troff
.if n \{\
.    ds #H 0
.    ds #V .8m
.    ds #F .3m
.    ds #[ \f1
.    ds #] \fP
.\}
.if t \{\
.    ds #H ((1u-(\\\\n(.fu%2u))*.13m)
.    ds #V .6m
.    ds #F 0
.    ds #[ \&
.    ds #] \&
.\}
.    \" simple accents for nroff and troff
.if n \{\
.    ds ' \&
.    ds ` \&
.    ds ^ \&
.    ds , \&
.    ds ~ ~
.    ds /
.\}
.if t \{\
.    ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
.    ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
.    ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
.    ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
.    ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
.    ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
.    \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
.    \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
.    \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
.    ds : e
.    ds 8 ss
.    ds o a
.    ds d- d\h'-1'\(ga
.    ds D- D\h'-1'\(hy
.    ds th \o'bp'
.    ds Th \o'LP'
.    ds ae ae
.    ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLMOD 1"
.TH PERLMOD 1 "2002-11-24" "perl v5.8.0" "Perl Programmers Reference Guide"
.SH "NAME"
perlmod \- Perl modules (packages and symbol tables)
.SH "DESCRIPTION"
.IX Header "DESCRIPTION"
.Sh "Packages"
.IX Subsection "Packages"
Perl provides a mechanism for alternative namespaces to protect
packages from stomping on each other's variables.  In fact, there's
really no such thing as a global variable in Perl.  The package
statement declares the compilation unit as being in the given
namespace.  The scope of the package declaration is from the
declaration itself through the end of the enclosing block, \f(CW\*(C`eval\*(C'\fR,
or file, whichever comes first (the same scope as the \fImy()\fR and
\&\fIlocal()\fR operators).  Unqualified dynamic identifiers will be in
this namespace, except for those few identifiers that if unqualified,
default to the main package instead of the current one as described
below.  A package statement affects only dynamic variables\*(--including
those you've used \fIlocal()\fR on\*(--but \fInot\fR lexical variables created
with \fImy()\fR.  Typically it would be the first declaration in a file
included by the \f(CW\*(C`do\*(C'\fR, \f(CW\*(C`require\*(C'\fR, or \f(CW\*(C`use\*(C'\fR operators.  You can
switch into a package in more than one place; it merely influences
which symbol table is used by the compiler for the rest of that
block.  You can refer to variables and filehandles in other packages
by prefixing the identifier with the package name and a double
colon: \f(CW$Package::Variable\fR.  If the package name is null, the
\&\f(CW\*(C`main\*(C'\fR package is assumed.  That is, \f(CW$::sail\fR is equivalent to
\&\f(CW$main::sail\fR.
.PP
The old package delimiter was a single quote, but double colon is now the
preferred delimiter, in part because it's more readable to humans, and
in part because it's more readable to \fBemacs\fR macros.  It also makes \*(C+
programmers feel like they know what's going on\*(--as opposed to using the
single quote as separator, which was there to make Ada programmers feel
like they knew what's going on.  Because the old-fashioned syntax is still
supported for backwards compatibility, if you try to use a string like
\&\f(CW"This is $owner's house"\fR, you'll be accessing \f(CW$owner::s\fR; that is,
the \f(CW$s\fR variable in package \f(CW\*(C`owner\*(C'\fR, which is probably not what you meant.
Use braces to disambiguate, as in \f(CW"This is ${owner}'s house"\fR.
.PP
Packages may themselves contain package separators, as in
\&\f(CW$OUTER::INNER::var\fR.  This implies nothing about the order of
name lookups, however.  There are no relative packages: all symbols
are either local to the current package, or must be fully qualified
from the outer package name down.  For instance, there is nowhere
within package \f(CW\*(C`OUTER\*(C'\fR that \f(CW$INNER::var\fR refers to
\&\f(CW$OUTER::INNER::var\fR.  It would treat package \f(CW\*(C`INNER\*(C'\fR as a totally
separate global package.
.PP
Only identifiers starting with letters (or underscore) are stored
in a package's symbol table.  All other symbols are kept in package
\&\f(CW\*(C`main\*(C'\fR, including all punctuation variables, like \f(CW$_\fR.  In addition,
when unqualified, the identifiers \s-1STDIN\s0, \s-1STDOUT\s0, \s-1STDERR\s0, \s-1ARGV\s0,
\&\s-1ARGVOUT\s0, \s-1ENV\s0, \s-1INC\s0, and \s-1SIG\s0 are forced to be in package \f(CW\*(C`main\*(C'\fR,
even when used for other purposes than their built-in one.  If you
have a package called \f(CW\*(C`m\*(C'\fR, \f(CW\*(C`s\*(C'\fR, or \f(CW\*(C`y\*(C'\fR, then you can't use the
qualified form of an identifier because it would be instead interpreted
as a pattern match, a substitution, or a transliteration.
.PP
Variables beginning with underscore used to be forced into package
main, but we decided it was more useful for package writers to be able
to use leading underscore to indicate private variables and method names.
\&\f(CW$_\fR is still global though.  See also
\&\*(L"Technical Note on the Syntax of Variable Names\*(R" in perlvar.
.PP
\&\f(CW\*(C`eval\*(C'\fRed strings are compiled in the package in which the \fIeval()\fR was
compiled.  (Assignments to \f(CW$SIG{}\fR, however, assume the signal
handler specified is in the \f(CW\*(C`main\*(C'\fR package.  Qualify the signal handler
name if you wish to have a signal handler in a package.)  For an
example, examine \fIperldb.pl\fR in the Perl library.  It initially switches
to the \f(CW\*(C`DB\*(C'\fR package so that the debugger doesn't interfere with variables
in the program you are trying to debug.  At various points, however, it
temporarily switches back to the \f(CW\*(C`main\*(C'\fR package to evaluate various
expressions in the context of the \f(CW\*(C`main\*(C'\fR package (or wherever you came
from).  See perldebug.
.PP
The special symbol \f(CW\*(C`_\|_PACKAGE_\|_\*(C'\fR contains the current package, but cannot
(easily) be used to construct variables.
.PP
See perlsub for other scoping issues related to \fImy()\fR and \fIlocal()\fR,
and perlref regarding closures.
.Sh "Symbol Tables"
.IX Subsection "Symbol Tables"
The symbol table for a package happens to be stored in the hash of that
name with two colons appended.  The main symbol table's name is thus
\&\f(CW%main::\fR, or \f(CW%::\fR for short.  Likewise the symbol table for the nested
package mentioned earlier is named \f(CW%OUTER::INNER::\fR.
.PP
The value in each entry of the hash is what you are referring to when you
use the \f(CW*name\fR typeglob notation.  In fact, the following have the same
effect, though the first is more efficient because it does the symbol
table lookups at compile time:
.PP
.Vb 2
\&    local *main::foo    = *main::bar;
\&    local $main::{foo}  = $main::{bar};
.Ve
.PP
(Be sure to note the \fBvast\fR difference between the second line above
and \f(CW\*(C`local $main::foo = $main::bar\*(C'\fR. The former is accessing the hash
\&\f(CW%main::\fR, which is the symbol table of package \f(CW\*(C`main\*(C'\fR. The latter is
simply assigning scalar \f(CW$bar\fR in package \f(CW\*(C`main\*(C'\fR to scalar \f(CW$foo\fR of
the same package.)
.PP
You can use this to print out all the variables in a package, for
instance.  The standard but antiquated \fIdumpvar.pl\fR library and
the \s-1CPAN\s0 module Devel::Symdump make use of this.
.PP
Assignment to a typeglob performs an aliasing operation, i.e.,
.PP
.Vb 1
\&    *dick = *richard;
.Ve
.PP
causes variables, subroutines, formats, and file and directory handles
accessible via the identifier \f(CW\*(C`richard\*(C'\fR also to be accessible via the
identifier \f(CW\*(C`dick\*(C'\fR.  If you want to alias only a particular variable or
subroutine, assign a reference instead:
.PP
.Vb 1
\&    *dick = \e$richard;
.Ve
.PP
Which makes \f(CW$richard\fR and \f(CW$dick\fR the same variable, but leaves
\&\f(CW@richard\fR and \f(CW@dick\fR as separate arrays.  Tricky, eh?
.PP
There is one subtle difference between the following statements:
.PP
.Vb 2
\&    *foo = *bar;
\&    *foo = \e$bar;
.Ve
.PP
\&\f(CW\*(C`*foo = *bar\*(C'\fR makes the typeglobs themselves synonymous while
\&\f(CW\*(C`*foo = \e$bar\*(C'\fR makes the \s-1SCALAR\s0 portions of two distinct typeglobs
refer to the same scalar value. This means that the following code:
.PP
.Vb 2
\&    $bar = 1;
\&    *foo = \e$bar;       # Make $foo an alias for $bar
.Ve
.PP
.Vb 4
\&    {
\&        local $bar = 2; # Restrict changes to block
\&        print $foo;     # Prints '1'!
\&    }
.Ve
.PP
Would print '1', because \f(CW$foo\fR holds a reference to the \fIoriginal\fR
\&\f(CW$bar\fR \*(-- the one that was stuffed away by \f(CW\*(C`local()\*(C'\fR and which will be
restored when the block ends. Because variables are accessed through the
typeglob, you can use \f(CW\*(C`*foo = *bar\*(C'\fR to create an alias which can be
localized. (But be aware that this means you can't have a separate
\&\f(CW@foo\fR and \f(CW@bar\fR, etc.)
.PP
What makes all of this important is that the Exporter module uses glob
aliasing as the import/export mechanism. Whether or not you can properly
localize a variable that has been exported from a module depends on how
it was exported:
.PP
.Vb 2
\&    @EXPORT = qw($FOO); # Usual form, can't be localized
\&    @EXPORT = qw(*FOO); # Can be localized
.Ve
.PP
You can work around the first case by using the fully qualified name 
(\f(CW$Package::FOO\fR) where you need a local value, or by overriding it
by saying \f(CW\*(C`*FOO = *Package::FOO\*(C'\fR in your script.
.PP
The \f(CW\*(C`*x = \e$y\*(C'\fR mechanism may be used to pass and return cheap references
into or from subroutines if you don't want to copy the whole
thing.  It only works when assigning to dynamic variables, not
lexicals.
.PP
.Vb 9
\&    %some_hash = ();                    # can't be my()
\&    *some_hash = fn( \e%another_hash );
\&    sub fn {
\&        local *hashsym = shift;
\&        # now use %hashsym normally, and you
\&        # will affect the caller's %another_hash
\&        my %nhash = (); # do what you want
\&        return \e%nhash;
\&    }
.Ve
.PP
On return, the reference will overwrite the hash slot in the
symbol table specified by the *some_hash typeglob.  This
is a somewhat tricky way of passing around references cheaply
when you don't want to have to remember to dereference variables
explicitly.
.PP
Another use of symbol tables is for making \*(L"constant\*(R" scalars.
.PP
.Vb 1
\&    *PI = \e3.14159265358979;
.Ve
.PP
Now you cannot alter \f(CW$PI\fR, which is probably a good thing all in all.
This isn't the same as a constant subroutine, which is subject to
optimization at compile\-time.  A constant subroutine is one prototyped
to take no arguments and to return a constant expression.  See 
perlsub for details on these.  The \f(CW\*(C`use constant\*(C'\fR pragma is a
convenient shorthand for these.
.PP
You can say \f(CW*foo{PACKAGE}\fR and \f(CW*foo{NAME}\fR to find out what name and
package the *foo symbol table entry comes from.  This may be useful
in a subroutine that gets passed typeglobs as arguments:
.PP
.Vb 6
\&    sub identify_typeglob {
\&        my $glob = shift;
\&        print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME}, "\en";
\&    }
\&    identify_typeglob *foo;
\&    identify_typeglob *bar::baz;
.Ve
.PP
This prints
.PP
.Vb 2
\&    You gave me main::foo
\&    You gave me bar::baz
.Ve
.PP
The \f(CW*foo{THING}\fR notation can also be used to obtain references to the
individual elements of *foo.  See perlref.
.PP
Subroutine definitions (and declarations, for that matter) need
not necessarily be situated in the package whose symbol table they
occupy.  You can define a subroutine outside its package by
explicitly qualifying the name of the subroutine:
.PP
.Vb 2
\&    package main;
\&    sub Some_package::foo { ... }   # &foo defined in Some_package
.Ve
.PP
This is just a shorthand for a typeglob assignment at compile time:
.PP
.Vb 1
\&    BEGIN { *Some_package::foo = sub { ... } }
.Ve
.PP
and is \fInot\fR the same as writing:
.PP
.Vb 4
\&    {
\&        package Some_package;
\&        sub foo { ... }
\&    }
.Ve
.PP
In the first two versions, the body of the subroutine is
lexically in the main package, \fInot\fR in Some_package. So
something like this:
.PP
.Vb 1
\&    package main;
.Ve
.PP
.Vb 2
\&    $Some_package::name = "fred";
\&    $main::name = "barney";
.Ve
.PP
.Vb 3
\&    sub Some_package::foo {
\&        print "in ", __PACKAGE__, ": \e$name is '$name'\en";
\&    }
.Ve
.PP
.Vb 1
\&    Some_package::foo();
.Ve
.PP
prints:
.PP
.Vb 1
\&    in main: $name is 'barney'
.Ve
.PP
rather than:
.PP
.Vb 1
\&    in Some_package: $name is 'fred'
.Ve
.PP
This also has implications for the use of the \s-1SUPER::\s0 qualifier
(see perlobj).
.Sh "Package Constructors and Destructors"
.IX Subsection "Package Constructors and Destructors"
Four special subroutines act as package constructors and destructors.
These are the \f(CW\*(C`BEGIN\*(C'\fR, \f(CW\*(C`CHECK\*(C'\fR, \f(CW\*(C`INIT\*(C'\fR, and \f(CW\*(C`END\*(C'\fR routines.  The
\&\f(CW\*(C`sub\*(C'\fR is optional for these routines.
.PP
A \f(CW\*(C`BEGIN\*(C'\fR subroutine is executed as soon as possible, that is, the moment
it is completely defined, even before the rest of the containing file
is parsed.  You may have multiple \f(CW\*(C`BEGIN\*(C'\fR blocks within a file\*(--they
will execute in order of definition.  Because a \f(CW\*(C`BEGIN\*(C'\fR block executes
immediately, it can pull in definitions of subroutines and such from other
files in time to be visible to the rest of the file.  Once a \f(CW\*(C`BEGIN\*(C'\fR
has run, it is immediately undefined and any code it used is returned to
Perl's memory pool.  This means you can't ever explicitly call a \f(CW\*(C`BEGIN\*(C'\fR.
.PP
An \f(CW\*(C`END\*(C'\fR subroutine is executed as late as possible, that is, after
perl has finished running the program and just before the interpreter
is being exited, even if it is exiting as a result of a \fIdie()\fR function.
(But not if it's polymorphing into another program via \f(CW\*(C`exec\*(C'\fR, or
being blown out of the water by a signal\*(--you have to trap that yourself
(if you can).)  You may have multiple \f(CW\*(C`END\*(C'\fR blocks within a file\*(--they
will execute in reverse order of definition; that is: last in, first
out (\s-1LIFO\s0).  \f(CW\*(C`END\*(C'\fR blocks are not executed when you run perl with the
\&\f(CW\*(C`\-c\*(C'\fR switch, or if compilation fails.
.PP
Inside an \f(CW\*(C`END\*(C'\fR subroutine, \f(CW$?\fR contains the value that the program is
going to pass to \f(CW\*(C`exit()\*(C'\fR.  You can modify \f(CW$?\fR to change the exit
value of the program.  Beware of changing \f(CW$?\fR by accident (e.g. by
running something via \f(CW\*(C`system\*(C'\fR).
.PP
Similar to \f(CW\*(C`BEGIN\*(C'\fR blocks, \f(CW\*(C`INIT\*(C'\fR blocks are run just before the
Perl runtime begins execution, in \*(L"first in, first out\*(R" (\s-1FIFO\s0) order.
For example, the code generators documented in perlcc make use of
\&\f(CW\*(C`INIT\*(C'\fR blocks to initialize and resolve pointers to XSUBs.
.PP
Similar to \f(CW\*(C`END\*(C'\fR blocks, \f(CW\*(C`CHECK\*(C'\fR blocks are run just after the
Perl compile phase ends and before the run time begins, in
\&\s-1LIFO\s0 order.  \f(CW\*(C`CHECK\*(C'\fR blocks are again useful in the Perl compiler
suite to save the compiled state of the program.
.PP
When you use the \fB\-n\fR and \fB\-p\fR switches to Perl, \f(CW\*(C`BEGIN\*(C'\fR and
\&\f(CW\*(C`END\*(C'\fR work just as they do in \fBawk\fR, as a degenerate case.
Both \f(CW\*(C`BEGIN\*(C'\fR and \f(CW\*(C`CHECK\*(C'\fR blocks are run when you use the \fB\-c\fR
switch for a compile-only syntax check, although your main code
is not.
.Sh "Perl Classes"
.IX Subsection "Perl Classes"
There is no special class syntax in Perl, but a package may act
as a class if it provides subroutines to act as methods.  Such a
package may also derive some of its methods from another class (package)
by listing the other package name(s) in its global \f(CW@ISA\fR array (which 
must be a package global, not a lexical).
.PP
For more on this, see perltoot and perlobj.
.Sh "Perl Modules"
.IX Subsection "Perl Modules"
A module is just a set of related functions in a library file, i.e.,
a Perl package with the same name as the file.  It is specifically 
designed to be reusable by other modules or programs.  It may do this
by providing a mechanism for exporting some of its symbols into the
symbol table of any package using it.  Or it may function as a class
definition and make its semantics available implicitly through
method calls on the class and its objects, without explicitly
exporting anything.  Or it can do a little of both.
.PP
For example, to start a traditional, non-OO module called Some::Module,
create a file called \fISome/Module.pm\fR and start with this template:
.PP
.Vb 1
\&    package Some::Module;  # assumes Some/Module.pm
.Ve
.PP
.Vb 2
\&    use strict;
\&    use warnings;
.Ve
.PP
.Vb 3
\&    BEGIN {
\&        use Exporter   ();
\&        our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
.Ve
.PP
.Vb 4
\&        # set the version for version checking
\&        $VERSION     = 1.00;
\&        # if using RCS/CVS, this may be preferred
\&        $VERSION = do { my @r = (q$Revision: 2.21 $ =~ /\ed+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker
.Ve
.PP
.Vb 3
\&        @ISA         = qw(Exporter);
\&        @EXPORT      = qw(&func1 &func2 &func4);
\&        %EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],
.Ve
.PP
.Vb 5
\&        # your exported package globals go here,
\&        # as well as any optionally exported functions
\&        @EXPORT_OK   = qw($Var1 %Hashit &func3);
\&    }
\&    our @EXPORT_OK;
.Ve
.PP
.Vb 3
\&    # exported package globals go here
\&    our $Var1;
\&    our %Hashit;
.Ve
.PP
.Vb 3
\&    # non-exported package globals go here
\&    our @more;
\&    our $stuff;
.Ve
.PP
.Vb 3
\&    # initialize package globals, first exported ones
\&    $Var1   = '';
\&    %Hashit = ();
.Ve
.PP
.Vb 3
\&    # then the others (which are still accessible as $Some::Module::stuff)
\&    $stuff  = '';
\&    @more   = ();
.Ve
.PP
.Vb 2
\&    # all file-scoped lexicals must be created before
\&    # the functions below that use them.
.Ve
.PP
.Vb 3
\&    # file-private lexicals go here
\&    my $priv_var    = '';
\&    my %secret_hash = ();
.Ve
.PP
.Vb 5
\&    # here's a file-private function as a closure,
\&    # callable as &$priv_func;  it cannot be prototyped.
\&    my $priv_func = sub {
\&        # stuff goes here.
\&    };
.Ve
.PP
.Vb 5
\&    # make all your functions, whether exported or not;
\&    # remember to put something interesting in the {} stubs
\&    sub func1      {}    # no prototype
\&    sub func2()    {}    # proto'd void
\&    sub func3($$)  {}    # proto'd to 2 scalars
.Ve
.PP
.Vb 2
\&    # this one isn't exported, but could be called!
\&    sub func4(\e%)  {}    # proto'd to 1 hash ref
.Ve
.PP
.Vb 1
\&    END { }       # module clean-up code here (global destructor)
.Ve
.PP
.Vb 1
\&    ## YOUR CODE GOES HERE
.Ve
.PP
.Vb 1
\&    1;  # don't forget to return a true value from the file
.Ve
.PP
Then go on to declare and use your variables in functions without
any qualifications.  See Exporter and the perlmodlib for
details on mechanics and style issues in module creation.
.PP
Perl modules are included into your program by saying
.PP
.Vb 1
\&    use Module;
.Ve
.PP
or
.PP
.Vb 1
\&    use Module LIST;
.Ve
.PP
This is exactly equivalent to
.PP
.Vb 1
\&    BEGIN { require Module; import Module; }
.Ve
.PP
or
.PP
.Vb 1
\&    BEGIN { require Module; import Module LIST; }
.Ve
.PP
As a special case
.PP
.Vb 1
\&    use Module ();
.Ve
.PP
is exactly equivalent to
.PP
.Vb 1
\&    BEGIN { require Module; }
.Ve
.PP
All Perl module files have the extension \fI.pm\fR.  The \f(CW\*(C`use\*(C'\fR operator
assumes this so you don't have to spell out "\fIModule.pm\fR" in quotes.
This also helps to differentiate new modules from old \fI.pl\fR and
\&\fI.ph\fR files.  Module names are also capitalized unless they're
functioning as pragmas; pragmas are in effect compiler directives,
and are sometimes called \*(L"pragmatic modules\*(R" (or even \*(L"pragmata\*(R"
if you're a classicist).
.PP
The two statements:
.PP
.Vb 2
\&    require SomeModule;
\&    require "SomeModule.pm";
.Ve
.PP
differ from each other in two ways.  In the first case, any double
colons in the module name, such as \f(CW\*(C`Some::Module\*(C'\fR, are translated
into your system's directory separator, usually \*(L"/\*(R".   The second
case does not, and would have to be specified literally.  The other
difference is that seeing the first \f(CW\*(C`require\*(C'\fR clues in the compiler
that uses of indirect object notation involving \*(L"SomeModule\*(R", as
in \f(CW\*(C`$ob = purge SomeModule\*(C'\fR, are method calls, not function calls.
(Yes, this really can make a difference.)
.PP
Because the \f(CW\*(C`use\*(C'\fR statement implies a \f(CW\*(C`BEGIN\*(C'\fR block, the importing
of semantics happens as soon as the \f(CW\*(C`use\*(C'\fR statement is compiled,
before the rest of the file is compiled.  This is how it is able
to function as a pragma mechanism, and also how modules are able to
declare subroutines that are then visible as list or unary operators for
the rest of the current file.  This will not work if you use \f(CW\*(C`require\*(C'\fR
instead of \f(CW\*(C`use\*(C'\fR.  With \f(CW\*(C`require\*(C'\fR you can get into this problem:
.PP
.Vb 2
\&    require Cwd;                # make Cwd:: accessible
\&    $here = Cwd::getcwd();
.Ve
.PP
.Vb 2
\&    use Cwd;                    # import names from Cwd::
\&    $here = getcwd();
.Ve
.PP
.Vb 2
\&    require Cwd;                # make Cwd:: accessible
\&    $here = getcwd();           # oops! no main::getcwd()
.Ve
.PP
In general, \f(CW\*(C`use Module ()\*(C'\fR is recommended over \f(CW\*(C`require Module\*(C'\fR,
because it determines module availability at compile time, not in the
middle of your program's execution.  An exception would be if two modules
each tried to \f(CW\*(C`use\*(C'\fR each other, and each also called a function from
that other module.  In that case, it's easy to use \f(CW\*(C`require\*(C'\fRs instead.
.PP
Perl packages may be nested inside other package names, so we can have
package names containing \f(CW\*(C`::\*(C'\fR.  But if we used that package name
directly as a filename it would make for unwieldy or impossible
filenames on some systems.  Therefore, if a module's name is, say,
\&\f(CW\*(C`Text::Soundex\*(C'\fR, then its definition is actually found in the library
file \fIText/Soundex.pm\fR.
.PP
Perl modules always have a \fI.pm\fR file, but there may also be
dynamically linked executables (often ending in \fI.so\fR) or autoloaded
subroutine definitions (often ending in \fI.al\fR) associated with the
module.  If so, these will be entirely transparent to the user of
the module.  It is the responsibility of the \fI.pm\fR file to load
(or arrange to autoload) any additional functionality.  For example,
although the \s-1POSIX\s0 module happens to do both dynamic loading and
autoloading, the user can say just \f(CW\*(C`use POSIX\*(C'\fR to get it all.
.Sh "Making your module threadsafe"
.IX Subsection "Making your module threadsafe"
Perl has since 5.6.0 support for a new type of threads called
interpreter threads. These threads can be used explicitly and implicitly.
.PP
Ithreads work by cloning the data tree so that no data is shared
between different threads. These threads can be used using the threads
module or by doing \fIfork()\fR on win32 (fake \fIfork()\fR support). When a
thread is cloned all Perl data is cloned, however non-Perl data cannot
be cloned automatically.  Perl after 5.7.2 has support for the \f(CW\*(C`CLONE\*(C'\fR 
special subroutine .  In \f(CW\*(C`CLONE\*(C'\fR you can do whatever you need to do,
like for example handle the cloning of non-Perl data, if necessary.
\&\f(CW\*(C`CLONE\*(C'\fR will be executed once for every package that has it defined
(or inherits it).  It will be called in the context of the new thread,
so all modifications are made in the new area.
.PP
If you want to \s-1CLONE\s0 all objects you will need to keep track of them per
package. This is simply done using a hash and \fIScalar::Util::weaken()\fR.
.SH "SEE ALSO"
.IX Header "SEE ALSO"
See perlmodlib for general style issues related to building Perl
modules and classes, as well as descriptions of the standard library
and \s-1CPAN\s0, Exporter for how Perl's standard import/export mechanism
works, perltoot and perltooc for an in-depth tutorial on
creating classes, perlobj for a hard-core reference document on
objects, perlsub for an explanation of functions and scoping,
and perlxstut and perlguts for more information on writing
extension modules.

Bell Labs OSI certified Powered by Plan 9

(Return to Plan 9 Home Page)

Copyright © 2021 Plan 9 Foundation. All Rights Reserved.
Comments to [email protected].