perlmod.pod
来自「视频监控网络部分的协议ddns,的模块的实现代码,请大家大胆指正.」· POD 代码 · 共 608 行 · 第 1/2 页
POD
608 行
=head1 NAMEperlmod - Perl modules (packages and symbol tables)=head1 DESCRIPTION=head2 PackagesX<package> X<namespace> X<variable, global> X<global variable> X<global>Perl provides a mechanism for alternative namespaces to protectpackages from stomping on each other's variables. In fact, there'sreally no such thing as a global variable in Perl. The packagestatement declares the compilation unit as being in the givennamespace. The scope of the package declaration is from thedeclaration itself through the end of the enclosing block, C<eval>,or file, whichever comes first (the same scope as the my() andlocal() operators). Unqualified dynamic identifiers will be inthis namespace, except for those few identifiers that if unqualified,default to the main package instead of the current one as describedbelow. A package statement affects only dynamic variables--includingthose you've used local() on--but I<not> lexical variables createdwith my(). Typically it would be the first declaration in a fileincluded by the C<do>, C<require>, or C<use> operators. You canswitch into a package in more than one place; it merely influenceswhich symbol table is used by the compiler for the rest of thatblock. You can refer to variables and filehandles in other packagesby prefixing the identifier with the package name and a doublecolon: C<$Package::Variable>. If the package name is null, theC<main> package is assumed. That is, C<$::sail> is equivalent toC<$main::sail>.The old package delimiter was a single quote, but double colon is now thepreferred delimiter, in part because it's more readable to humans, andin part because it's more readable to B<emacs> macros. It also makes C++programmers feel like they know what's going on--as opposed to using thesingle quote as separator, which was there to make Ada programmers feellike they knew what was going on. Because the old-fashioned syntax is stillsupported for backwards compatibility, if you try to use a string likeC<"This is $owner's house">, you'll be accessing C<$owner::s>; that is,the $s variable in package C<owner>, which is probably not what you meant.Use braces to disambiguate, as in C<"This is ${owner}'s house">.X<::> X<'>Packages may themselves contain package separators, as inC<$OUTER::INNER::var>. This implies nothing about the order ofname lookups, however. There are no relative packages: all symbolsare either local to the current package, or must be fully qualifiedfrom the outer package name down. For instance, there is nowherewithin package C<OUTER> that C<$INNER::var> refers toC<$OUTER::INNER::var>. C<INNER> refers to a totallyseparate global package.Only identifiers starting with letters (or underscore) are storedin a package's symbol table. All other symbols are kept in packageC<main>, including all punctuation variables, like $_. In addition,when unqualified, the identifiers STDIN, STDOUT, STDERR, ARGV,ARGVOUT, ENV, INC, and SIG are forced to be in package C<main>,even when used for other purposes than their built-in ones. If youhave a package called C<m>, C<s>, or C<y>, then you can't use thequalified form of an identifier because it would be instead interpretedas a pattern match, a substitution, or a transliteration.X<variable, punctuation> Variables beginning with underscore used to be forced into packagemain, but we decided it was more useful for package writers to be ableto use leading underscore to indicate private variables and method names.However, variables and functions named with a single C<_>, such as$_ and C<sub _>, are still forced into the package C<main>. See alsoL<perlvar/"Technical Note on the Syntax of Variable Names">.C<eval>ed strings are compiled in the package in which the eval() wascompiled. (Assignments to C<$SIG{}>, however, assume the signalhandler specified is in the C<main> package. Qualify the signal handlername if you wish to have a signal handler in a package.) For anexample, examine F<perldb.pl> in the Perl library. It initially switchesto the C<DB> package so that the debugger doesn't interfere with variablesin the program you are trying to debug. At various points, however, ittemporarily switches back to the C<main> package to evaluate variousexpressions in the context of the C<main> package (or wherever you camefrom). See L<perldebug>.The special symbol C<__PACKAGE__> contains the current package, but cannot(easily) be used to construct variable names.See L<perlsub> for other scoping issues related to my() and local(),and L<perlref> regarding closures.=head2 Symbol TablesX<symbol table> X<stash> X<%::> X<%main::> X<typeglob> X<glob> X<alias>The symbol table for a package happens to be stored in the hash of thatname with two colons appended. The main symbol table's name is thusC<%main::>, or C<%::> for short. Likewise the symbol table for the nestedpackage mentioned earlier is named C<%OUTER::INNER::>.The value in each entry of the hash is what you are referring to when youuse the C<*name> typeglob notation. In fact, the following have the sameeffect, though the first is more efficient because it does the symboltable lookups at compile time: local *main::foo = *main::bar; local $main::{foo} = $main::{bar};(Be sure to note the B<vast> difference between the second line aboveand C<local $main::foo = $main::bar>. The former is accessing the hashC<%main::>, which is the symbol table of package C<main>. The latter issimply assigning scalar C<$bar> in package C<main> to scalar C<$foo> ofthe same package.)You can use this to print out all the variables in a package, forinstance. The standard but antiquated F<dumpvar.pl> library andthe CPAN module Devel::Symdump make use of this.Assignment to a typeglob performs an aliasing operation, i.e., *dick = *richard;causes variables, subroutines, formats, and file and directory handlesaccessible via the identifier C<richard> also to be accessible via theidentifier C<dick>. If you want to alias only a particular variable orsubroutine, assign a reference instead: *dick = \$richard;Which makes $richard and $dick the same variable, but leaves@richard and @dick as separate arrays. Tricky, eh?There is one subtle difference between the following statements: *foo = *bar; *foo = \$bar;C<*foo = *bar> makes the typeglobs themselves synonymous whileC<*foo = \$bar> makes the SCALAR portions of two distinct typeglobsrefer to the same scalar value. This means that the following code: $bar = 1; *foo = \$bar; # Make $foo an alias for $bar { local $bar = 2; # Restrict changes to block print $foo; # Prints '1'! }Would print '1', because C<$foo> holds a reference to the I<original>C<$bar> -- the one that was stuffed away by C<local()> and which will berestored when the block ends. Because variables are accessed through thetypeglob, you can use C<*foo = *bar> to create an alias which can belocalized. (But be aware that this means you can't have a separateC<@foo> and C<@bar>, etc.)What makes all of this important is that the Exporter module uses globaliasing as the import/export mechanism. Whether or not you can properlylocalize a variable that has been exported from a module depends on howit was exported: @EXPORT = qw($FOO); # Usual form, can't be localized @EXPORT = qw(*FOO); # Can be localizedYou can work around the first case by using the fully qualified name(C<$Package::FOO>) where you need a local value, or by overriding itby saying C<*FOO = *Package::FOO> in your script.The C<*x = \$y> mechanism may be used to pass and return cheap referencesinto or from subroutines if you don't want to copy the wholething. It only works when assigning to dynamic variables, notlexicals. %some_hash = (); # can't be my() *some_hash = fn( \%another_hash ); sub fn { local *hashsym = shift; # now use %hashsym normally, and you # will affect the caller's %another_hash my %nhash = (); # do what you want return \%nhash; }On return, the reference will overwrite the hash slot in thesymbol table specified by the *some_hash typeglob. Thisis a somewhat tricky way of passing around references cheaplywhen you don't want to have to remember to dereference variablesexplicitly.Another use of symbol tables is for making "constant" scalars.X<constant> X<scalar, constant> *PI = \3.14159265358979;Now you cannot alter C<$PI>, which is probably a good thing all in all.This isn't the same as a constant subroutine, which is subject tooptimization at compile-time. A constant subroutine is one prototypedto take no arguments and to return a constant expression. SeeL<perlsub> for details on these. The C<use constant> pragma is aconvenient shorthand for these.You can say C<*foo{PACKAGE}> and C<*foo{NAME}> to find out what name andpackage the *foo symbol table entry comes from. This may be usefulin a subroutine that gets passed typeglobs as arguments: sub identify_typeglob { my $glob = shift; print 'You gave me ', *{$glob}{PACKAGE}, '::', *{$glob}{NAME}, "\n"; } identify_typeglob *foo; identify_typeglob *bar::baz;This prints You gave me main::foo You gave me bar::bazThe C<*foo{THING}> notation can also be used to obtain references to theindividual elements of *foo. See L<perlref>.Subroutine definitions (and declarations, for that matter) neednot necessarily be situated in the package whose symbol table theyoccupy. You can define a subroutine outside its package byexplicitly qualifying the name of the subroutine: package main; sub Some_package::foo { ... } # &foo defined in Some_packageThis is just a shorthand for a typeglob assignment at compile time: BEGIN { *Some_package::foo = sub { ... } }and is I<not> the same as writing: { package Some_package; sub foo { ... } }In the first two versions, the body of the subroutine islexically in the main package, I<not> in Some_package. Sosomething like this: package main; $Some_package::name = "fred"; $main::name = "barney"; sub Some_package::foo { print "in ", __PACKAGE__, ": \$name is '$name'\n"; } Some_package::foo();prints: in main: $name is 'barney'rather than: in Some_package: $name is 'fred'This also has implications for the use of the SUPER:: qualifier(see L<perlobj>).=head2 BEGIN, UNITCHECK, CHECK, INIT and ENDX<BEGIN> X<UNITCHECK> X<CHECK> X<INIT> X<END>Five specially named code blocks are executed at the beginning and atthe end of a running Perl program. These are the C<BEGIN>,C<UNITCHECK>, C<CHECK>, C<INIT>, and C<END> blocks.These code blocks can be prefixed with C<sub> to give the appearance of asubroutine (although this is not considered good style). One should notethat these code blocks don't really exist as named subroutines (despitetheir appearance). The thing that gives this away is the fact that you canhave B<more than one> of these code blocks in a program, and they will getB<all> executed at the appropriate moment. So you can't execute any ofthese code blocks by name.A C<BEGIN> code block is executed as soon as possible, that is, the momentit is completely defined, even before the rest of the containing file (orstring) is parsed. You may have multiple C<BEGIN> blocks within a file (oreval'ed string) -- they will execute in order of definition. Because a C<BEGIN>code block executes immediately, it can pull in definitions of subroutinesand such from other files in time to be visible to the rest of the compileand run time. Once a C<BEGIN> has run, it is immediately undefined and anycode it used is returned to Perl's memory pool.It should be noted that C<BEGIN> and C<UNITCHECK> code blocks B<are>executed inside string C<eval()>'s. The C<CHECK> and C<INIT> codeblocks are B<not> executed inside a string eval, which e.g. can be aproblem in a mod_perl environment.An C<END> code block 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 morphing 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.Note that C<END> code blocks are B<not> executed at the end of a stringC<eval()>: if any C<END> code blocks are created in a string C<eval()>,they will be executed just as any other C<END> code block of that packagein LIFO order just before the interpreter is being exited.
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?