I would like to expose all subs into my namespace without having to list them one at a time:
@EXPORT = qw( firstsub secondsub third sub etc );
Using fully qualified names would require bunch of change to existing code so I'd rather not do that.
Is there @EXPORT_ALL?
I think documentation says it's a bad idea, but I'd like to do it anyway, or at least know how.
To answer Jon's why: right now for quick refactoring I want to move of bunch of subs into their own package with least hassle and code changes to the existing scripts (where those subs are currenty used and often repeated).
Also, mostly, I was just curious. (since it seemed like that Exporter might as well have that as standard feature, but somewhat surprisingly based on answers so far it doesn't)
1 Basic export functionality. For a module to export one or more identifiers into a caller's namespace, it must: use the Exporter module, which is part of the standard Perl distribution, declare the module to inherit Exporter's capabilities, by setting the variable @ISA (see Section 7.3.
@EXPORT and @EXPORT_OK are the two main variables used during export operation. @EXPORT contains list of symbols (subroutines and variables) of the module to be exported into the caller namespace. @EXPORT_OK does export of symbols on demand basis.
It is typically used to add extra directories to Perl's search path so that later do, require, and use statements will find library files that aren't located in Perl's default search path.
The differences are many and often subtle:use only expects a bareword, require can take a bareword or an expression. use is evaluated at compile-time, require at run-time. use implicitly calls the import method of the module being loaded, require does not.
Don't do any exporting at all, and don't declare a package name in your library. Just load the file with require
and everything will be in the current package. Easy peasy.
Don't. But if you really want to... write a custom import
that walks the symbol table and export all the named subroutines.
# Export all subs in package. Not for use in production code!
sub import {
no strict 'refs';
my $caller = caller;
while (my ($name, $symbol) = each %{__PACKAGE__ . '::'}) {
next if $name eq 'BEGIN'; # don't export BEGIN blocks
next if $name eq 'import'; # don't export this sub
next unless *{$symbol}{CODE}; # export subs only
my $imported = $caller . '::' . $name;
*{ $imported } = \*{ $symbol };
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With