Документация
HTML CSS PHP PERL другое

Section 15.3.  @EXPORT and @EXPORT_OK

 
Previous
Table of Contents
Next

15.3. @EXPORT and @EXPORT_OK

The import provided by Exporter examines the @EXPORT variable in the module's package to determine which variables it exports by default. For example, File::Basename might do something like:

package File::Basename;
our @EXPORT = qw( basename dirname fileparse );
use base qw(Exporter);

The @EXPORT list both defines a list of available subroutines for export (the public interface) and provides a default list for Perl to use when we don't specify an import list. For example, these two calls are equivalent:

use File::Basename;

BEGIN { require File::Basename; File::Basename->import }

We pass no list to import. In that case, the Exporter->import routine looks at @EXPORT and provides everything in the list.[Section 15.3.  @EXPORT and @EXPORT_OK]

[Section 15.3.  @EXPORT and @EXPORT_OK] Remember, having no list is not the same as having an empty list. If the list is empty, the module's import method is simply not called at all.

What if we had subroutines we didn't want as part of the default import but that would still be available if we asked for them? We can add those subroutines to the @EXPORT_OK list in the module's package. For example, suppose that Gilligan's module provides the guess_direction_toward routine by default but could also provide the ask_the_skipper_about and get_north_from_professor routines, if requested. We can start it like this:

package Navigate::SeatOfPants;
our @EXPORT = qw(guess_direction_toward);
our @EXPORT_OK = qw(ask_the_skipper_about get_north_from_professor);
use base qw(Exporter);

The following invocations would then be valid:

use Navigate::SeatOfPants;  # gets guess_direction_toward

use Navigate::SeatOfPants qw(guess_direction_toward); # same

use Navigate::SeatOfPants
  qw(guess_direction_toward ask_the_skipper_about);

use Navigate::SeatOfPants
  qw(ask_the_skipper_about get_north_from_professor);
  ## does NOT import guess_direction_toward!

If we specify any names, they must be in either @EXPORT or @EXPORT_OK, so this request is rejected by Exporter->import:

use Navigate::SeatOfPants qw(according_to_GPS);

because according_to_GPS is in neither @EXPORT nor @EXPORT_OK.[*] Thus, with those two arrays, we have control over our public interface. This does not stop someone from saying Navigate::SeatOfPants::according_to_GPS (if it existed), but at least now it's obvious that they're using something we didn't intend to offer them.

[*] This check also catches misspellings and mistaken subroutine names, keeping you from wondering why the get_direction_from_professor routine isn't working.


Previous
Table of Contents
Next
© 2000- NIV