Leaked source code of windows server 2003
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.

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