📄 exporter.pm
字号:
@EXPORT_OK = qw ($b); sub import { $A::b = 1; A->export_to_level(1, @_); }This will export the symbols one level 'above' the current package - ie: to the program or module that used package A. Note: Be careful not to modify C<@_> at all before you call export_to_level- or people using your package will get very unexplained results!=head2 Exporting without inheriting from ExporterBy including Exporter in your @ISA you inherit an Exporter's import() methodbut you also inherit several other helper methods which you probably don'twant. To avoid this you can do package YourModule; use Exporter qw( import );which will export Exporter's own import() method into YourModule.Everything will work as before but you won't need to include Exporter in@YourModule::ISA.Note: This feature was introduced in version 5.57of Exporter, released with perl 5.8.3.=head2 Module Version CheckingThe Exporter module will convert an attempt to import a number from amodule into a call to $module_name-E<gt>require_version($value). This canbe used to validate that the version of the module being used isgreater than or equal to the required version.The Exporter module supplies a default require_version method whichchecks the value of $VERSION in the exporting module.Since the default require_version method treats the $VERSION 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.=head2 Managing Unknown SymbolsIn 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.The names of any symbols that cannot be exported should be listedin the C<@EXPORT_FAIL> array.If 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: @failed_symbols = $module_name->export_fail(@failed_symbols);If 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.Uses for the export_fail method include giving better error messagesfor some symbols and performing lazy architectural checks (put moresymbols into @EXPORT_FAIL by default and then take them out if someoneactually tries to use them and an expensive check shows that they areusable on that platform).=head2 Tag Handling Utility FunctionsSince the symbols listed within %EXPORT_TAGS must also appear in either@EXPORT or @EXPORT_OK, two utility functions are provided which allowyou to easily add tagged sets of symbols to @EXPORT or @EXPORT_OK: %EXPORT_TAGS = (foo => [qw(aa bb cc)], bar => [qw(aa cc dd)]); Exporter::export_tags('foo'); # add aa, bb and cc to @EXPORT Exporter::export_ok_tags('bar'); # add aa, cc and dd to @EXPORT_OKAny names which are not tags are added to @EXPORT or @EXPORT_OKunchanged but will trigger a warning (with C<-w>) to avoid misspelt tagsnames being silently added to @EXPORT or @EXPORT_OK. Future versionsmay make this a fatal error.=head2 Generating combined tagsIf several symbol categories exist in %EXPORT_TAGS, it's usuallyuseful to create the utility ":all" to simplify "use" statements.The simplest way to do this is: %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; }CGI.pm creates an ":all" tag which contains some (but not reallyall) of its categories. That could be done with one smallchange: # 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/; }Note that the tag names in %EXPORT_TAGS don't have the leading ':'.=head2 C<AUTOLOAD>ed ConstantsMany modules make use of C<AUTOLOAD>ing for constant subroutines toavoid having to compile and waste memory on rarely used values (seeL<perlsub> 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.Even if a prototype is available at compile time, the body of thesubroutine is not (it hasn't been C<AUTOLOAD>ed yet). perl needs toexamine both the C<()> prototype and the body of a subroutine atcompile time to detect that it can safely replace calls to thatsubroutine with the constant value.A workaround for this is to call the constants once in a C<BEGIN> block: 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.This forces the C<AUTOLOAD> for C<SO_LINGER> to take place beforeSO_LINGER is encountered later in C<My> package.If you are writing a package that C<AUTOLOAD>s, consider forcingan C<AUTOLOAD> for any constants explicitly imported by other packagesor which are usually used when your package is C<use>d.=head1 Good Practices=head2 Declaring C<@EXPORT_OK> and FriendsWhen using C<Exporter> with the standard C<strict> and C<warnings>pragmas, the C<our> keyword is needed to declare the packagevariables C<@EXPORT_OK>, C<@EXPORT>, C<@ISA>, etc. our @ISA = qw(Exporter); our @EXPORT_OK = qw(munge frobnicate);If backward compatibility for Perls under 5.6 is important,one must write instead a C<use vars> statement. use vars qw(@ISA @EXPORT_OK); @ISA = qw(Exporter); @EXPORT_OK = qw(munge frobnicate);=head2 Playing SafeThere are some caveats with the use of runtime statementslike C<require Exporter> 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.The ideal (but a bit ugly) way to never have to thinkabout that is to use C<BEGIN> blocks. So the first partof the L</SYNOPSIS> code could be rewritten as: 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 }The C<BEGIN> will assure that the loading of F<Exporter.pm>and the assignments to C<@ISA> and C<@EXPORT_OK> happenimmediately, leaving no room for something to get awryor just plain wrong.With respect to loading C<Exporter> and inheriting, thereare alternatives with the use of modules like C<base> and C<parent>. use base qw( Exporter ); # or use parent qw( Exporter );Any of these statements are nice replacements forC<BEGIN { require Exporter; @ISA = qw(Exporter); }>with the same compile-time effect. The basic differenceis that C<base> code interacts with declared C<fields>while C<parent> is a streamlined version of the olderC<base> code to just establish the IS-A relationship.For more details, see the documentation and code ofL<base> and L<parent>.Another thorough remedy to that runtime vs. compile-time trap is to use L<Exporter::Easy>,which is a wrapper of Exporter that allows allboilerplate code at a single gulp in theuse statement. use Exporter::Easy ( OK => [ qw(munge frobnicate) ], ); # @ISA setup is automatic # all assignments happen at compile time=head2 What not to ExportYou have been warned already in L</Selecting What To Export>to not export:=over 4=item *method names (because you don't need toand that's likely to not do what you want),=item *anything by default (because you don't want to surprise your users...badly)=item *anything you don't need to (because less is more)=backThere's one more item to add to this list. Do B<not>export variable names. Just because C<Exporter> lets youdo that, it does not mean you should. @EXPORT_OK = qw( $svar @avar %hvar ); # DON'T!Exporting 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.To provide the capability to set/get class-widesettings, it is best instead to provide accessorsas subroutines or class methods instead.=head1 SEE ALSOC<Exporter> is definitely not the only module withsymbol exporter capabilities. At CPAN, 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. Exporter::Easy Exporter::Lite Exporter::Renaming Exporter::Tidy Sub::Exporter / Sub::Installer Perl6::Export / Perl6::Export::Attrs=head1 LICENSEThis library is free software. You can redistribute itand/or modify it under the same terms as Perl itself.=cut
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -