Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I redefined the import method of a module

package M1; use parent qw(Exporter); our @EXPORT; sub func{print "Hello"} sub import{print "Imported";@EXPORT=qw(func)} 1;

And EXPORT is not working

perl -I. -le 'use M1;func()' Imported Undefined subroutine &main::func called at -e line 1.

But when I don't redefine import function, EXPORT works fine

package M1; use parent qw(Exporter); our @EXPORT; sub func{print "Hello"} #sub import{print "Imported";@EXPORT=qw(func)} 1;
perl -I. -le 'use M1;func()' Hello
How can I get both redefining import and EXPORT to work?

Replies are listed 'Best First'.
Re: Redefined import method and EXPORT not working
by Corion (Patriarch) on Dec 22, 2014 at 08:11 UTC

    @EXPORT is not magical. It's just a variable. All the magic must happen in import.

    The easiest approach would be to use Exporter::import, and stash that away and at the end, pass control to it:

    use vars qw(@EXPORT $orig_import); use Exporter 'import'; sub my_import { print "Imported\n"; goto &$orig_import; }; BEGIN { # Install our own import routine over import: $orig_import= \&import; *import= \&my_import; };

      That seems like an over-complicated way of doing:

      use Exporter (); sub import { print "Imported\n"; goto \&Exporter::import; }
        Great!

      That worked

      package M1; use parent qw(Exporter); @EXPORT=qw(func); sub func{print "Hello"} sub import{ print "Imported"; print @_; M1->export_to_level(1,@_)} 1;
      perl -I. -we 'use M1 qw(func);func()'

        Please, don't inherit from Exporter. Just use use Exporter 'import';. Inheritance as a way of getting access to methods of a module is not what I consider a clean approach.