home *** CD-ROM | disk | FTP | other *** search
/ Acorn User 10 / AU_CD10.iso / Updates / Perl / Non-RPC / Docs / perlmod < prev    next >
Text File  |  1999-04-17  |  17KB  |  417 lines

  1. NAME
  2.     perlmod - Perl modules (packages and symbol tables)
  3.  
  4. DESCRIPTION
  5.   Packages
  6.  
  7.     Perl provides a mechanism for alternative namespaces to protect
  8.     packages from stomping on each other's variables. In fact,
  9.     there's really no such thing as a global variable in Perl
  10.     (although some identifiers default to the main package instead
  11.     of the current one). The package statement declares the
  12.     compilation unit as being in the given namespace. The scope of
  13.     the package declaration is from the declaration itself through
  14.     the end of the enclosing block, `eval', `sub', or end of file,
  15.     whichever comes first (the same scope as the my() and local()
  16.     operators). All further unqualified dynamic identifiers will be
  17.     in this namespace. A package statement only affects dynamic
  18.     variables--including those you've used local() on--but *not*
  19.     lexical variables created with my(). Typically it would be the
  20.     first declaration in a file to be included by the `require' or
  21.     `use' operator. You can switch into a package in more than one
  22.     place; it merely influences which symbol table is used by the
  23.     compiler for the rest of that block. You can refer to variables
  24.     and filehandles in other packages by prefixing the identifier
  25.     with the package name and a double colon: `$Package::Variable'.
  26.     If the package name is null, the `main' package is assumed. That
  27.     is, `$::sail' is equivalent to `$main::sail'.
  28.  
  29.     The old package delimiter was a single quote, but double colon
  30.     is now the preferred delimiter, in part because it's more
  31.     readable to humans, and in part because it's more readable to
  32.     emacs macros. It also makes C++ programmers feel like they know
  33.     what's going on--as opposed to using the single quote as
  34.     separator, which was there to make Ada programmers feel like
  35.     they knew what's going on. Because the old-fashioned syntax is
  36.     still supported for backwards compatibility, if you try to use a
  37.     string like `"This is $owner's house"', you'll be accessing
  38.     `$owner::s'; that is, the $s variable in package `owner', which
  39.     is probably not what you meant. Use braces to disambiguate, as
  40.     in `"This is ${owner}'s house"'.
  41.  
  42.     Packages may be nested inside other packages:
  43.     `$OUTER::INNER::var'. This implies nothing about the order of
  44.     name lookups, however. All symbols are either local to the
  45.     current package, or must be fully qualified from the outer
  46.     package name down. For instance, there is nowhere within package
  47.     `OUTER' that `$INNER::var' refers to `$OUTER::INNER::var'. It
  48.     would treat package `INNER' as a totally separate global
  49.     package.
  50.  
  51.     Only identifiers starting with letters (or underscore) are
  52.     stored in a package's symbol table. All other symbols are kept
  53.     in package `main', including all of the punctuation variables
  54.     like $_. In addition, when unqualified, the identifiers STDIN,
  55.     STDOUT, STDERR, ARGV, ARGVOUT, ENV, INC, and SIG are forced to
  56.     be in package `main', even when used for other purposes than
  57.     their builtin one. Note also that, if you have a package called
  58.     `m', `s', or `y', then you can't use the qualified form of an
  59.     identifier because it will be interpreted instead as a pattern
  60.     match, a substitution, or a transliteration.
  61.  
  62.     (Variables beginning with underscore used to be forced into
  63.     package main, but we decided it was more useful for package
  64.     writers to be able to use leading underscore to indicate private
  65.     variables and method names. $_ is still global though.)
  66.  
  67.     Eval()ed strings are compiled in the package in which the eval()
  68.     was compiled. (Assignments to `$SIG{}', however, assume the
  69.     signal handler specified is in the `main' package. Qualify the
  70.     signal handler name if you wish to have a signal handler in a
  71.     package.) For an example, examine perldb.pl in the Perl library.
  72.     It initially switches to the `DB' package so that the debugger
  73.     doesn't interfere with variables in the script you are trying to
  74.     debug. At various points, however, it temporarily switches back
  75.     to the `main' package to evaluate various expressions in the
  76.     context of the `main' package (or wherever you came from). See
  77.     the perldebug manpage.
  78.  
  79.     The special symbol `__PACKAGE__' contains the current package,
  80.     but cannot (easily) be used to construct variables.
  81.  
  82.     See the perlsub manpage for other scoping issues related to my()
  83.     and local(), and the perlref manpage regarding closures.
  84.  
  85.   Symbol Tables
  86.  
  87.     The symbol table for a package happens to be stored in the hash
  88.     of that name with two colons appended. The main symbol table's
  89.     name is thus `%main::', or `%::' for short. Likewise symbol
  90.     table for the nested package mentioned earlier is named
  91.     `%OUTER::INNER::'.
  92.  
  93.     The value in each entry of the hash is what you are referring to
  94.     when you use the `*name' typeglob notation. In fact, the
  95.     following have the same effect, though the first is more
  96.     efficient because it does the symbol table lookups at compile
  97.     time:
  98.  
  99.         local *main::foo    = *main::bar;
  100.         local $main::{foo}  = $main::{bar};
  101.  
  102.  
  103.     You can use this to print out all the variables in a package,
  104.     for instance. The standard dumpvar.pl library and the CPAN
  105.     module Devel::Symdump make use of this.
  106.  
  107.     Assignment to a typeglob performs an aliasing operation, i.e.,
  108.  
  109.         *dick = *richard;
  110.  
  111.  
  112.     causes variables, subroutines, formats, and file and directory
  113.     handles accessible via the identifier `richard' also to be
  114.     accessible via the identifier `dick'. If you want to alias only
  115.     a particular variable or subroutine, you can assign a reference
  116.     instead:
  117.  
  118.         *dick = \$richard;
  119.  
  120.  
  121.     Which makes $richard and $dick the same variable, but leaves
  122.     @richard and @dick as separate arrays. Tricky, eh?
  123.  
  124.     This mechanism may be used to pass and return cheap references
  125.     into or from subroutines if you won't want to copy the whole
  126.     thing. It only works when assigning to dynamic variables, not
  127.     lexicals.
  128.  
  129.         %some_hash = ();            # can't be my()
  130.         *some_hash = fn( \%another_hash );
  131.         sub fn {
  132.         local *hashsym = shift;
  133.         # now use %hashsym normally, and you
  134.         # will affect the caller's %another_hash
  135.         my %nhash = (); # do what you want
  136.         return \%nhash;
  137.         }
  138.  
  139.  
  140.     On return, the reference will overwrite the hash slot in the
  141.     symbol table specified by the *some_hash typeglob. This is a
  142.     somewhat tricky way of passing around references cheaply when
  143.     you won't want to have to remember to dereference variables
  144.     explicitly.
  145.  
  146.     Another use of symbol tables is for making "constant" scalars.
  147.  
  148.         *PI = \3.14159265358979;
  149.  
  150.  
  151.     Now you cannot alter $PI, which is probably a good thing all in
  152.     all. This isn't the same as a constant subroutine, which is
  153.     subject to optimization at compile-time. This isn't. A constant
  154.     subroutine is one prototyped to take no arguments and to return
  155.     a constant expression. See the perlsub manpage for details on
  156.     these. The `use constant' pragma is a convenient shorthand for
  157.     these.
  158.  
  159.     You can say `*foo{PACKAGE}' and `*foo{NAME}' to find out what
  160.     name and package the *foo symbol table entry comes from. This
  161.     may be useful in a subroutine that gets passed typeglobs as
  162.     arguments:
  163.  
  164.         sub identify_typeglob {
  165.             my $glob = shift;
  166.             print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME}, "\n";
  167.         }
  168.         identify_typeglob *foo;
  169.         identify_typeglob *bar::baz;
  170.  
  171.  
  172.     This prints
  173.  
  174.         You gave me main::foo
  175.         You gave me bar::baz
  176.  
  177.  
  178.     The *foo{THING} notation can also be used to obtain references
  179.     to the individual elements of *foo, see the perlref manpage.
  180.  
  181.   Package Constructors and Destructors
  182.  
  183.     There are two special subroutine definitions that function as
  184.     package constructors and destructors. These are the `BEGIN' and
  185.     `END' routines. The `sub' is optional for these routines.
  186.  
  187.     A `BEGIN' subroutine is executed as soon as possible, that is,
  188.     the moment it is completely defined, even before the rest of the
  189.     containing file is parsed. You may have multiple `BEGIN' blocks
  190.     within a file--they will execute in order of definition. Because
  191.     a `BEGIN' block executes immediately, it can pull in definitions
  192.     of subroutines and such from other files in time to be visible
  193.     to the rest of the file. Once a `BEGIN' has run, it is
  194.     immediately undefined and any code it used is returned to Perl's
  195.     memory pool. This means you can't ever explicitly call a
  196.     `BEGIN'.
  197.  
  198.     An `END' subroutine is executed as late as possible, that is,
  199.     when the interpreter is being exited, even if it is exiting as a
  200.     result of a die() function. (But not if it's polymorphing into
  201.     another program via `exec', or being blown out of the water by a
  202.     signal--you have to trap that yourself (if you can).) You may
  203.     have multiple `END' blocks within a file--they will execute in
  204.     reverse order of definition; that is: last in, first out (LIFO).
  205.  
  206.     Inside an `END' subroutine, `$?' contains the value that the
  207.     script is going to pass to `exit()'. You can modify `$?' to
  208.     change the exit value of the script. Beware of changing `$?' by
  209.     accident (e.g. by running something via `system').
  210.  
  211.     Note that when you use the -n and -p switches to Perl, `BEGIN'
  212.     and `END' work just as they do in awk, as a degenerate case. As
  213.     currently implemented (and subject to change, since its
  214.     inconvenient at best), both `BEGIN' *and* `END' blocks are run
  215.     when you use the -c switch for a compile-only syntax check,
  216.     although your main code is not.
  217.  
  218.   Perl Classes
  219.  
  220.     There is no special class syntax in Perl, but a package may
  221.     function as a class if it provides subroutines to act as
  222.     methods. Such a package may also derive some of its methods from
  223.     another class (package) by listing the other package name in its
  224.     global @ISA array (which must be a package global, not a
  225.     lexical).
  226.  
  227.     For more on this, see the perltoot manpage and the perlobj
  228.     manpage.
  229.  
  230.   Perl Modules
  231.  
  232.     A module is just a package that is defined in a library file of
  233.     the same name, and is designed to be reusable. It may do this by
  234.     providing a mechanism for exporting some of its symbols into the
  235.     symbol table of any package using it. Or it may function as a
  236.     class definition and make its semantics available implicitly
  237.     through method calls on the class and its objects, without
  238.     explicit exportation of any symbols. Or it can do a little of
  239.     both.
  240.  
  241.     For example, to start a normal module called Some::Module,
  242.     create a file called Some/Module.pm and start with this
  243.     template:
  244.  
  245.         package Some::Module;  # assumes Some/Module.pm
  246.  
  247.         use strict;
  248.  
  249.         BEGIN {
  250.             use Exporter   ();
  251.             use vars       qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
  252.  
  253.             # set the version for version checking
  254.             $VERSION     = 1.00;
  255.             # if using RCS/CVS, this may be preferred
  256.             $VERSION = do { my @r = (q$Revision: 2.21 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker
  257.  
  258.             @ISA         = qw(Exporter);
  259.             @EXPORT      = qw(&func1 &func2 &func4);
  260.             %EXPORT_TAGS = ( );     # eg: TAG => [ qw!name1 name2! ],
  261.  
  262.             # your exported package globals go here,
  263.             # as well as any optionally exported functions
  264.             @EXPORT_OK   = qw($Var1 %Hashit &func3);
  265.         }
  266.         use vars      @EXPORT_OK;
  267.  
  268.         # non-exported package globals go here
  269.         use vars      qw(@more $stuff);
  270.  
  271.         # initialize package globals, first exported ones
  272.         $Var1   = '';
  273.         %Hashit = ();
  274.  
  275.         # then the others (which are still accessible as $Some::Module::stuff)
  276.         $stuff  = '';
  277.         @more   = ();
  278.  
  279.         # all file-scoped lexicals must be created before
  280.         # the functions below that use them.
  281.  
  282.         # file-private lexicals go here
  283.         my $priv_var    = '';
  284.         my %secret_hash = ();
  285.  
  286.         # here's a file-private function as a closure,
  287.         # callable as &$priv_func;  it cannot be prototyped.
  288.         my $priv_func = sub {
  289.             # stuff goes here.
  290.         };
  291.  
  292.         # make all your functions, whether exported or not;
  293.         # remember to put something interesting in the {} stubs
  294.         sub func1      {}    # no prototype
  295.         sub func2()    {}    # proto'd void
  296.         sub func3($$)  {}    # proto'd to 2 scalars
  297.  
  298.         # this one isn't exported, but could be called!
  299.         sub func4(\%)  {}    # proto'd to 1 hash ref
  300.  
  301.         END { }       # module clean-up code here (global destructor)
  302.  
  303.  
  304.     Then go on to declare and use your variables in functions
  305.     without any qualifications. See the Exporter manpage and the the
  306.     perlmodlib manpage for details on mechanics and style issues in
  307.     module creation.
  308.  
  309.     Perl modules are included into your program by saying
  310.  
  311.         use Module;
  312.  
  313.  
  314.     or
  315.  
  316.         use Module LIST;
  317.  
  318.  
  319.     This is exactly equivalent to
  320.  
  321.         BEGIN { require Module; import Module; }
  322.  
  323.  
  324.     or
  325.  
  326.         BEGIN { require Module; import Module LIST; }
  327.  
  328.  
  329.     As a special case
  330.  
  331.         use Module ();
  332.  
  333.  
  334.     is exactly equivalent to
  335.  
  336.         BEGIN { require Module; }
  337.  
  338.  
  339.     All Perl module files have the extension .pm. `use' assumes this
  340.     so that you don't have to spell out "Module.pm" in quotes. This
  341.     also helps to differentiate new modules from old .pl and .ph
  342.     files. Module names are also capitalized unless they're
  343.     functioning as pragmas, "Pragmas" are in effect compiler
  344.     directives, and are sometimes called "pragmatic modules" (or
  345.     even "pragmata" if you're a classicist).
  346.  
  347.     The two statements:
  348.  
  349.         require SomeModule;
  350.         require "SomeModule.pm";        
  351.  
  352.  
  353.     differ from each other in two ways. In the first case, any
  354.     double colons in the module name, such as `Some::Module', are
  355.     translated into your system's directory separator, usually "/".
  356.     The second case does not, and would have to be specified
  357.     literally. The other difference is that seeing the first
  358.     `require' clues in the compiler that uses of indirect object
  359.     notation involving "SomeModule", as in `$ob = purge SomeModule',
  360.     are method calls, not function calls. (Yes, this really can make
  361.     a difference.)
  362.  
  363.     Because the `use' statement implies a `BEGIN' block, the
  364.     importation of semantics happens at the moment the `use'
  365.     statement is compiled, before the rest of the file is compiled.
  366.     This is how it is able to function as a pragma mechanism, and
  367.     also how modules are able to declare subroutines that are then
  368.     visible as list operators for the rest of the current file. This
  369.     will not work if you use `require' instead of `use'. With
  370.     require you can get into this problem:
  371.  
  372.         require Cwd;        # make Cwd:: accessible
  373.         $here = Cwd::getcwd();
  374.  
  375.         use Cwd;            # import names from Cwd::
  376.         $here = getcwd();
  377.  
  378.         require Cwd;            # make Cwd:: accessible
  379.         $here = getcwd();         # oops! no main::getcwd()
  380.  
  381.  
  382.     In general, `use Module ()' is recommended over `require
  383.     Module', because it determines module availability at compile
  384.     time, not in the middle of your program's execution. An
  385.     exception would be if two modules each tried to `use' each
  386.     other, and each also called a function from that other module.
  387.     In that case, it's easy to use `require's instead.
  388.  
  389.     Perl packages may be nested inside other package names, so we
  390.     can have package names containing `::'. But if we used that
  391.     package name directly as a filename it would makes for unwieldy
  392.     or impossible filenames on some systems. Therefore, if a
  393.     module's name is, say, `Text::Soundex', then its definition is
  394.     actually found in the library file Text/Soundex.pm.
  395.  
  396.     Perl modules always have a .pm file, but there may also be
  397.     dynamically linked executables or autoloaded subroutine
  398.     definitions associated with the module. If so, these will be
  399.     entirely transparent to the user of the module. It is the
  400.     responsibility of the .pm file to load (or arrange to autoload)
  401.     any additional functionality. The POSIX module happens to do
  402.     both dynamic loading and autoloading, but the user can say just
  403.     `use POSIX' to get it all.
  404.  
  405.     For more information on writing extension modules, see the
  406.     perlxstut manpage and the perlguts manpage.
  407.  
  408. SEE ALSO
  409.     See the perlmodlib manpage for general style issues related to
  410.     building Perl modules and classes as well as descriptions of the
  411.     standard library and CPAN, the Exporter manpage for how Perl's
  412.     standard import/export mechanism works, the perltoot manpage for
  413.     an in-depth tutorial on creating classes, the perlobj manpage
  414.     for a hard-core reference document on objects, and the perlsub
  415.     manpage for an explanation of functions and scoping.
  416.  
  417.