📄 perlmod.pod
字号:
=head1 NAMEperlmod - Perl modules (packages and symbol tables)=head1 DESCRIPTION=head2 PackagesPerl 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's 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">.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>. It would treat package C<INNER> as 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 one. 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.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.$_ is still global though. 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 variables.See L<perlsub> for other scoping issues related to my() and local(),and L<perlref> regarding closures.=head2 Symbol TablesThe 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?This 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. *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. See L<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 Package Constructors and DestructorsFour special subroutines act as package constructors and destructors.These are the C<BEGIN>, C<CHECK>, C<INIT>, and C<END> routines. TheC<sub> is optional for these routines.A C<BEGIN> subroutine is executed as soon as possible, that is, the momentit is completely defined, even before the rest of the containing fileis parsed. You may have multiple C<BEGIN> blocks within a file--theywill execute in order of definition. Because a C<BEGIN> block executes
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -