home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 2002 November / SGI IRIX Base Documentation 2002 November.iso / usr / share / catman / u_man / cat1 / perlmod.z / perlmod
Encoding:
Text File  |  2002-10-03  |  20.5 KB  |  529 lines

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