perl - Exporting symbols without Exporter -
i learning how use packages , objects in perl.
it has been suggested use exporter
in order use functions , variables of module have package
directive.
i curious know whether there way export symbols without using exporter
? in other words, can exporter
emulated in way?
the reason ask due assumption exporter carries overhead functionality small, simple scripts must run fast possible don't need, , avoided including functionality few simple lines of code.
maybe simple illustration of mean might help.
say have module this
my $my_string = "my_print"; sub my_print { print "$my_string: ", @_; }
which allow lot of small scripts use my_print
instead of print
, simple require
filename of module (and very little overhead).
then, wanted use in module has package declaration, , no longer works, must use package
declaration , therefore exporter
in simple module work in new module.
having been using perl quite while used fact quite simple, straightforward, , low overhead, feel there such solution this. if not, accept answer explains why exporter way.
what exporter quite simple. here's how can without using exporter:
in foo.pm:
package foo; use strict; use warnings; sub answer { 42 } sub import { no strict 'refs'; $caller = caller; *{$caller . "::answer"} = \&answer; } 1;
in script.pl:
use foo; print answer(), "\n";
however, others have said, needn't worry overhead of using exporter. it's small , efficient module, , has been bundled every version of perl since 5.0. whatsmore, chances you're loading somewhere anyway -- many of core perl modules (such carp, scalar::util, list::util, etc) use it.
update: in earlier version of code above, forgot no strict 'refs';
. necessary *{$some_string}
work.
Comments
Post a Comment