From dbef1d5621085812b828448df0547018bb71785d Mon Sep 17 00:00:00 2001 From: Chad Granum Date: Thu, 25 Aug 2016 21:56:19 -0700 Subject: Add import() --- README | 2 ++ lib/Importer.pm | 43 +++++++++++++++++++++++++++++++++++++++++-- t/import.t | 21 +++++++++++++++++++++ 3 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 t/import.t diff --git a/README b/README index 25cc1b5..dcee954 100644 --- a/README +++ b/README @@ -1,8 +1,10 @@ NAME + Importer - Alternative but compatible interface to modules that export symbols. DESCRIPTION + This module acts as a layer between Exporter and modules which consume exports. It is feature-compatible with Exporter, plus some much needed extras. You can use this to import symbols from any exporter that diff --git a/lib/Importer.pm b/lib/Importer.pm index aa64ebc..d58058f 100644 --- a/lib/Importer.pm +++ b/lib/Importer.pm @@ -17,7 +17,33 @@ our %IMPORTED; # This will be used to check if an import arg is a version number my %NUMERIC = map +($_ => 1), 0 .. 9; -sub IMPORTER_MENU() {(export_ok => [qw/optimal_import/])} +sub IMPORTER_MENU() { + return ( + export_ok => [qw/optimal_import/], + export_anon => { + import => sub { + my $class = shift; + my @caller = caller(0); + + _version_check($class, \@caller, shift @_) if @_ && $NUMERIC{substr($_[0], 0, 1)}; + + return unless @_; + + my $file = _mod_to_file($class); + _load_file(\@caller, $file) unless $INC{$file}; + + return if optimal_import($class, $caller[0], \@caller, @_); + + my $self = $class->new( + from => $class, + caller => \@caller, + ); + + $self->do_import($caller[0], @_); + }, + }, + ); +} ########################################################################### # @@ -1541,7 +1567,7 @@ imports then only the LAST one will be used. These can be imported: - use Importer 'Importer' => qw/optimal_import/; + use Importer 'Importer' => qw/import optimal_import/; =over 4 @@ -1556,6 +1582,19 @@ If the import is successful this will return true. If the import is unsuccessful this will return false, and no modifications to the symbol table will occur. +=item $class->import(@imports) + +If you write class intended to be used with L, but also need to +provide a legacy C method for direct consumers of your class, you can +import this C method. + + package My::Exporter; + + # This will give you 'import()' much like 'use base "Exporter";' + use Importer 'Importer' => qw/import/; + + ... + =back =head1 SOURCE diff --git a/t/import.t b/t/import.t new file mode 100644 index 0000000..b21faa7 --- /dev/null +++ b/t/import.t @@ -0,0 +1,21 @@ +use strict; +use warnings; +use Test::More; + +BEGIN { + $INC{'My/Exporter.pm'} = 1; + + use Importer Importer => qw/import/; + + our @EXPORT = qw/foo/; + + sub foo { 'foo' } +} + +use My::Exporter; + +can_ok(__PACKAGE__, qw/foo/); + +is(foo(), 'foo', "foo() imported"); + +done_testing; -- cgit v1.2.3