📄 perlmod.pod
字号:
immediately, it can pull in definitions of subroutines and such from otherfiles in time to be visible to the rest of the file. Once a C<BEGIN>has run, it is immediately undefined and any code it used is returned toPerl's memory pool. This means you can't ever explicitly call a C<BEGIN>.An C<END> subroutine is executed as late as possible, that is, afterperl has finished running the program and just before the interpreteris being exited, even if it is exiting as a result of a die() function.(But not if it's polymorphing into another program via C<exec>, orbeing blown out of the water by a signal--you have to trap that yourself(if you can).) You may have multiple C<END> blocks within a file--theywill execute in reverse order of definition; that is: last in, firstout (LIFO). C<END> blocks are not executed when you run perl with theC<-c> switch, or if compilation fails.Inside an C<END> subroutine, C<$?> contains the value that the program isgoing to pass to C<exit()>. You can modify C<$?> to change the exitvalue of the program. Beware of changing C<$?> by accident (e.g. byrunning something via C<system>).Similar to C<BEGIN> blocks, C<INIT> blocks are run just before thePerl runtime begins execution, in "first in, first out" (FIFO) order.For example, the code generators documented in L<perlcc> make use ofC<INIT> blocks to initialize and resolve pointers to XSUBs.Similar to C<END> blocks, C<CHECK> blocks are run just after thePerl compile phase ends and before the run time begins, inLIFO order. C<CHECK> blocks are again useful in the Perl compilersuite to save the compiled state of the program.When you use the B<-n> and B<-p> switches to Perl, C<BEGIN> andC<END> work just as they do in B<awk>, as a degenerate case.Both C<BEGIN> and C<CHECK> blocks are run when you use the B<-c>switch for a compile-only syntax check, although your main codeis not.=head2 Perl ClassesThere is no special class syntax in Perl, but a package may actas a class if it provides subroutines to act as methods. Such apackage may also derive some of its methods from another class (package)by listing the other package name(s) in its global @ISA array (which must be a package global, not a lexical).For more on this, see L<perltoot> and L<perlobj>.=head2 Perl ModulesA module is just a set of related functions in a library file, i.e.,a Perl package with the same name as the file. It is specifically designed to be reusable by other modules or programs. It may do thisby providing a mechanism for exporting some of its symbols into thesymbol table of any package using it. Or it may function as a classdefinition and make its semantics available implicitly throughmethod calls on the class and its objects, without explicitlyexporting anything. Or it can do a little of both.For example, to start a traditional, non-OO module called Some::Module,create a file called F<Some/Module.pm> and start with this template: package Some::Module; # assumes Some/Module.pm use strict; use warnings; BEGIN { use Exporter (); our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS); # set the version for version checking $VERSION = 1.00; # if using RCS/CVS, this may be preferred $VERSION = do { my @r = (q$Revision: 2.21 $ =~ /\d+/g); sprintf "%d."."%02d" x $#r, @r }; # must be all one line, for MakeMaker @ISA = qw(Exporter); @EXPORT = qw(&func1 &func2 &func4); %EXPORT_TAGS = ( ); # eg: TAG => [ qw!name1 name2! ], # your exported package globals go here, # as well as any optionally exported functions @EXPORT_OK = qw($Var1 %Hashit &func3); } our @EXPORT_OK; # exported package globals go here our $Var1; our %Hashit; # non-exported package globals go here our @more; our $stuff; # initialize package globals, first exported ones $Var1 = ''; %Hashit = (); # then the others (which are still accessible as $Some::Module::stuff) $stuff = ''; @more = (); # all file-scoped lexicals must be created before # the functions below that use them. # file-private lexicals go here my $priv_var = ''; my %secret_hash = (); # here's a file-private function as a closure, # callable as &$priv_func; it cannot be prototyped. my $priv_func = sub { # stuff goes here. }; # make all your functions, whether exported or not; # remember to put something interesting in the {} stubs sub func1 {} # no prototype sub func2() {} # proto'd void sub func3($$) {} # proto'd to 2 scalars # this one isn't exported, but could be called! sub func4(\%) {} # proto'd to 1 hash ref END { } # module clean-up code here (global destructor) ## YOUR CODE GOES HERE 1; # don't forget to return a true value from the fileThen go on to declare and use your variables in functions withoutany qualifications. See L<Exporter> and the L<perlmodlib> fordetails on mechanics and style issues in module creation.Perl modules are included into your program by saying use Module;or use Module LIST;This is exactly equivalent to BEGIN { require Module; import Module; }or BEGIN { require Module; import Module LIST; }As a special case use Module ();is exactly equivalent to BEGIN { require Module; }All Perl module files have the extension F<.pm>. The C<use> operatorassumes this so you don't have to spell out "F<Module.pm>" in quotes.This also helps to differentiate new modules from old F<.pl> andF<.ph> files. Module names are also capitalized unless they'refunctioning as pragmas; pragmas are in effect compiler directives,and are sometimes called "pragmatic modules" (or even "pragmata"if you're a classicist).The two statements: require SomeModule; require "SomeModule.pm"; differ from each other in two ways. In the first case, any doublecolons in the module name, such as C<Some::Module>, are translatedinto your system's directory separator, usually "/". The secondcase does not, and would have to be specified literally. The otherdifference is that seeing the first C<require> clues in the compilerthat uses of indirect object notation involving "SomeModule", asin C<$ob = purge SomeModule>, are method calls, not function calls.(Yes, this really can make a difference.)Because the C<use> statement implies a C<BEGIN> block, the importingof semantics happens as soon as the C<use> statement is compiled,before the rest of the file is compiled. This is how it is ableto function as a pragma mechanism, and also how modules are able todeclare subroutines that are then visible as list or unary operators forthe rest of the current file. This will not work if you use C<require>instead of C<use>. With C<require> you can get into this problem: require Cwd; # make Cwd:: accessible $here = Cwd::getcwd(); use Cwd; # import names from Cwd:: $here = getcwd(); require Cwd; # make Cwd:: accessible $here = getcwd(); # oops! no main::getcwd()In general, C<use Module ()> is recommended over C<require Module>,because it determines module availability at compile time, not in themiddle of your program's execution. An exception would be if two moduleseach tried to C<use> each other, and each also called a function fromthat other module. In that case, it's easy to use C<require>s instead.Perl packages may be nested inside other package names, so we can havepackage names containing C<::>. But if we used that package namedirectly as a filename it would make for unwieldy or impossiblefilenames on some systems. Therefore, if a module's name is, say,C<Text::Soundex>, then its definition is actually found in the libraryfile F<Text/Soundex.pm>.Perl modules always have a F<.pm> file, but there may also bedynamically linked executables (often ending in F<.so>) or autoloadedsubroutine definitions (often ending in F<.al>) associated with themodule. If so, these will be entirely transparent to the user ofthe module. It is the responsibility of the F<.pm> file to load(or arrange to autoload) any additional functionality. For example,although the POSIX module happens to do both dynamic loading andautoloading, the user can say just C<use POSIX> to get it all.=head1 SEE ALSOSee L<perlmodlib> for general style issues related to building Perlmodules and classes, as well as descriptions of the standard libraryand CPAN, L<Exporter> for how Perl's standard import/export mechanismworks, L<perltoot> and L<perltootc> for an in-depth tutorial oncreating classes, L<perlobj> for a hard-core reference document onobjects, L<perlsub> for an explanation of functions and scoping,and L<perlxstut> and L<perlguts> for more information on writingextension modules.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -