Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

375 lines
16 KiB

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