Exporter - Export function
The Exporter module allows you to export a function from a module.
# Package declaration package Your Module; # Inherit Exporter use Exporter 'import'; # Write the function to export our @EXPORT = qw/func1 func2/; # Write an exportable function our @EXPORT_OK = qw/func3 func4/; # Function sub func1 {...} sub func2 {...} sub func3 {...} sub func4 {...}
When you create a module using Exporter, the function is imported when you use the module.
If you execute use in the form of "use module name;", the functions included in @EXPORT will be imported.
# The functions (func1 and func2) included in @EXPORT are imported. use Your Module;
When executed in the form of "use module name argument 1 argument 2 ..", the function included in @EXPORT_OK or @EXPORT and specified by the argument is imported.
# @EXPORT_OK or the functions contained in @EXPORT (func2, func3 and func4) are imported use YourModule qw/func2 func3 func4/;
@EXPORT, @EXPORT_OK are a package variable.
Exporter module export mechanism
I would like to explain a little about how the Exporter module works. The first thing you should know is that when you run use, it will automatically call the import method of the specified module. This example tries to execute the import method of YourModule.
The import method is not defined in YourModule, but since you are importing the import method of the Exporter module, the import method of the Exporter is called.
In the import method of Exporter, the process of exporting the function to the calling package is described. Let's write a process to export the function written in @EXPORT to the calling package so that the atmosphere can be conveyed.
sub import { # First argument of use (YourModule in this example) my $class = shift; # Caller's package (main in this example) my $caller = caller; # Export function no strict'refs'; foreach my $func (@{"${class}::EXPORT"}) { * {"${caller}::$func"} = \&{"${class}::$func"}; } }
Which way to write the Exporter module
There are multiple ways to write the Exporter module, and you can write as follows.
# Part 1 use Exporter 'import'; # 2 push @ISA, 'Exporter'; # 3 use base 'Exporter';
Here is the first one that seems to be the most intuitive.