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