📄 exporter.3
字号:
For example, suppose that you have a module, A, which already has animport function:.PP.Vb 1\& package A;\&\& @ISA = qw(Exporter);\& @EXPORT_OK = qw ($b);\&\& sub import\& {\& $A::b = 1; # not a very useful import method\& }.Ve.PPand you want to Export symbol \f(CW$A::b\fR back to the module that called package A. Since Exporter relies on the import method to work, via inheritance, as it stands \fIExporter::import()\fR will never get called. Instead, say the following:.PP.Vb 3\& package A;\& @ISA = qw(Exporter);\& @EXPORT_OK = qw ($b);\&\& sub import\& {\& $A::b = 1;\& A\->export_to_level(1, @_);\& }.Ve.PPThis will export the symbols one level 'above' the current package \- ie: to the program or module that used package A..PPNote: Be careful not to modify \f(CW@_\fR at all before you call export_to_level\&\- or people using your package will get very unexplained results!.Sh "Exporting without inheriting from Exporter".IX Subsection "Exporting without inheriting from Exporter"By including Exporter in your \f(CW@ISA\fR you inherit an Exporter's \fIimport()\fR methodbut you also inherit several other helper methods which you probably don'twant. To avoid this you can do.PP.Vb 2\& package YourModule;\& use Exporter qw( import );.Ve.PPwhich will export Exporter's own \fIimport()\fR method into YourModule.Everything will work as before but you won't need to include Exporter in\&\f(CW@YourModule::ISA\fR..PPNote: This feature was introduced in version 5.57of Exporter, released with perl 5.8.3..Sh "Module Version Checking".IX Subsection "Module Version Checking"The Exporter module will convert an attempt to import a number from amodule into a call to \f(CW$module_name\fR\->require_version($value). This canbe used to validate that the version of the module being used isgreater than or equal to the required version..PPThe Exporter module supplies a default require_version method whichchecks the value of \f(CW$VERSION\fR in the exporting module..PPSince the default require_version method treats the \f(CW$VERSION\fR number asa simple numeric value it will regard version 1.10 as lower than1.9. For this reason it is strongly recommended that you use numberswith at least two decimal places, e.g., 1.09..Sh "Managing Unknown Symbols".IX Subsection "Managing Unknown Symbols"In some situations you may want to prevent certain symbols from beingexported. Typically this applies to extensions which have functionsor constants that may not exist on some systems..PPThe names of any symbols that cannot be exported should be listedin the \f(CW@EXPORT_FAIL\fR array..PPIf a module attempts to import any of these symbols the Exporterwill give the module an opportunity to handle the situation beforegenerating an error. The Exporter will call an export_fail methodwith a list of the failed symbols:.PP.Vb 1\& @failed_symbols = $module_name\->export_fail(@failed_symbols);.Ve.PPIf the export_fail method returns an empty list then no error isrecorded and all the requested symbols are exported. If the returnedlist is not empty then an error is generated for each symbol and theexport fails. The Exporter provides a default export_fail method whichsimply returns the list unchanged..PPUses for the export_fail method include giving better error messagesfor some symbols and performing lazy architectural checks (put moresymbols into \f(CW@EXPORT_FAIL\fR by default and then take them out if someoneactually tries to use them and an expensive check shows that they areusable on that platform)..Sh "Tag Handling Utility Functions".IX Subsection "Tag Handling Utility Functions"Since the symbols listed within \f(CW%EXPORT_TAGS\fR must also appear in either\&\f(CW@EXPORT\fR or \f(CW@EXPORT_OK\fR, two utility functions are provided which allowyou to easily add tagged sets of symbols to \f(CW@EXPORT\fR or \f(CW@EXPORT_OK:\fR.PP.Vb 1\& %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);\&\& Exporter::export_tags(\*(Aqfoo\*(Aq); # add aa, bb and cc to @EXPORT\& Exporter::export_ok_tags(\*(Aqbar\*(Aq); # add aa, cc and dd to @EXPORT_OK.Ve.PPAny names which are not tags are added to \f(CW@EXPORT\fR or \f(CW@EXPORT_OK\fRunchanged but will trigger a warning (with \f(CW\*(C`\-w\*(C'\fR) to avoid misspelt tagsnames being silently added to \f(CW@EXPORT\fR or \f(CW@EXPORT_OK\fR. Future versionsmay make this a fatal error..Sh "Generating combined tags".IX Subsection "Generating combined tags"If several symbol categories exist in \f(CW%EXPORT_TAGS\fR, it's usuallyuseful to create the utility \*(L":all\*(R" to simplify \*(L"use\*(R" statements..PPThe simplest way to do this is:.PP.Vb 1\& %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]);\&\& # add all the other ":class" tags to the ":all" class,\& # deleting duplicates\& {\& my %seen;\&\& push @{$EXPORT_TAGS{all}},\& grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}} foreach keys %EXPORT_TAGS;\& }.Ve.PP\&\s-1CGI\s0.pm creates an \*(L":all\*(R" tag which contains some (but not reallyall) of its categories. That could be done with one smallchange:.PP.Vb 4\& # add some of the other ":class" tags to the ":all" class,\& # deleting duplicates\& {\& my %seen;\&\& push @{$EXPORT_TAGS{all}},\& grep {!$seen{$_}++} @{$EXPORT_TAGS{$_}}\& foreach qw/html2 html3 netscape form cgi internal/;\& }.Ve.PPNote that the tag names in \f(CW%EXPORT_TAGS\fR don't have the leading ':'..ie n .Sh """AUTOLOAD""ed Constants".el .Sh "\f(CWAUTOLOAD\fPed Constants".IX Subsection "AUTOLOADed Constants"Many modules make use of \f(CW\*(C`AUTOLOAD\*(C'\fRing for constant subroutines toavoid having to compile and waste memory on rarely used values (seeperlsub for details on constant subroutines). Calls to suchconstant subroutines are not optimized away at compile time becausethey can't be checked at compile time for constancy..PPEven if a prototype is available at compile time, the body of thesubroutine is not (it hasn't been \f(CW\*(C`AUTOLOAD\*(C'\fRed yet). perl needs toexamine both the \f(CW\*(C`()\*(C'\fR prototype and the body of a subroutine atcompile time to detect that it can safely replace calls to thatsubroutine with the constant value..PPA workaround for this is to call the constants once in a \f(CW\*(C`BEGIN\*(C'\fR block:.PP.Vb 1\& package My ;\&\& use Socket ;\&\& foo( SO_LINGER ); ## SO_LINGER NOT optimized away; called at runtime\& BEGIN { SO_LINGER }\& foo( SO_LINGER ); ## SO_LINGER optimized away at compile time..Ve.PPThis forces the \f(CW\*(C`AUTOLOAD\*(C'\fR for \f(CW\*(C`SO_LINGER\*(C'\fR to take place before\&\s-1SO_LINGER\s0 is encountered later in \f(CW\*(C`My\*(C'\fR package..PPIf you are writing a package that \f(CW\*(C`AUTOLOAD\*(C'\fRs, consider forcingan \f(CW\*(C`AUTOLOAD\*(C'\fR for any constants explicitly imported by other packagesor which are usually used when your package is \f(CW\*(C`use\*(C'\fRd..SH "Good Practices".IX Header "Good Practices".ie n .Sh "Declaring @EXPORT_OK and Friends".el .Sh "Declaring \f(CW@EXPORT_OK\fP and Friends".IX Subsection "Declaring @EXPORT_OK and Friends"When using \f(CW\*(C`Exporter\*(C'\fR with the standard \f(CW\*(C`strict\*(C'\fR and \f(CW\*(C`warnings\*(C'\fRpragmas, the \f(CW\*(C`our\*(C'\fR keyword is needed to declare the packagevariables \f(CW@EXPORT_OK\fR, \f(CW@EXPORT\fR, \f(CW@ISA\fR, etc..PP.Vb 2\& our @ISA = qw(Exporter);\& our @EXPORT_OK = qw(munge frobnicate);.Ve.PPIf backward compatibility for Perls under 5.6 is important,one must write instead a \f(CW\*(C`use vars\*(C'\fR statement..PP.Vb 3\& use vars qw(@ISA @EXPORT_OK);\& @ISA = qw(Exporter);\& @EXPORT_OK = qw(munge frobnicate);.Ve.Sh "Playing Safe".IX Subsection "Playing Safe"There are some caveats with the use of runtime statementslike \f(CW\*(C`require Exporter\*(C'\fR and the assignment to packagevariables, which can very subtle for the unaware programmer.This may happen for instance with mutually recursivemodules, which are affected by the time the relevantconstructions are executed..PPThe ideal (but a bit ugly) way to never have to thinkabout that is to use \f(CW\*(C`BEGIN\*(C'\fR blocks. So the first partof the \*(L"\s-1SYNOPSIS\s0\*(R" code could be rewritten as:.PP.Vb 1\& package YourModule;\&\& use strict;\& use warnings;\&\& our (@ISA, @EXPORT_OK);\& BEGIN {\& require Exporter;\& @ISA = qw(Exporter);\& @EXPORT_OK = qw(munge frobnicate); # symbols to export on request\& }.Ve.PPThe \f(CW\*(C`BEGIN\*(C'\fR will assure that the loading of \fIExporter.pm\fRand the assignments to \f(CW@ISA\fR and \f(CW@EXPORT_OK\fR happenimmediately, leaving no room for something to get awryor just plain wrong..PPWith respect to loading \f(CW\*(C`Exporter\*(C'\fR and inheriting, thereare alternatives with the use of modules like \f(CW\*(C`base\*(C'\fR and \f(CW\*(C`parent\*(C'\fR..PP.Vb 3\& use base qw( Exporter );\& # or\& use parent qw( Exporter );.Ve.PPAny of these statements are nice replacements for\&\f(CW\*(C`BEGIN { require Exporter; @ISA = qw(Exporter); }\*(C'\fRwith the same compile-time effect. The basic differenceis that \f(CW\*(C`base\*(C'\fR code interacts with declared \f(CW\*(C`fields\*(C'\fRwhile \f(CW\*(C`parent\*(C'\fR is a streamlined version of the older\&\f(CW\*(C`base\*(C'\fR code to just establish the IS-A relationship..PPFor more details, see the documentation and code ofbase and parent..PPAnother thorough remedy to that runtime vs. compile-time trap is to use Exporter::Easy,which is a wrapper of Exporter that allows allboilerplate code at a single gulp in theuse statement..PP.Vb 5\& use Exporter::Easy (\& OK => [ qw(munge frobnicate) ],\& );\& # @ISA setup is automatic\& # all assignments happen at compile time.Ve.Sh "What not to Export".IX Subsection "What not to Export"You have been warned already in \*(L"Selecting What To Export\*(R"to not export:.IP "\(bu" 4method names (because you don't need toand that's likely to not do what you want),.IP "\(bu" 4anything by default (because you don't want to surprise your users...badly).IP "\(bu" 4anything you don't need to (because less is more).PPThere's one more item to add to this list. Do \fBnot\fRexport variable names. Just because \f(CW\*(C`Exporter\*(C'\fR lets youdo that, it does not mean you should..PP.Vb 1\& @EXPORT_OK = qw( $svar @avar %hvar ); # DON\*(AqT!.Ve.PPExporting variables is not a good idea. They canchange under the hood, provoking horribleeffects at-a-distance, that are too hard to trackand to fix. Trust me: they are not worth it..PPTo provide the capability to set/get class-widesettings, it is best instead to provide accessorsas subroutines or class methods instead..SH "SEE ALSO".IX Header "SEE ALSO"\&\f(CW\*(C`Exporter\*(C'\fR is definitely not the only module withsymbol exporter capabilities. At \s-1CPAN\s0, you may finda bunch of them. Some are lighter. Someprovide improved APIs and features. Peek the onethat fits your needs. The following isa sample list of such modules..PP.Vb 6\& Exporter::Easy\& Exporter::Lite\& Exporter::Renaming\& Exporter::Tidy\& Sub::Exporter / Sub::Installer\& Perl6::Export / Perl6::Export::Attrs.Ve.SH "LICENSE".IX Header "LICENSE"This library is free software. You can redistribute itand/or modify it under the same terms as Perl itself.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -