in reply to Exporter. Correct way to override import?

Veltro:

As you know, your program breaks because it interferes with the import function provided by Exporter. This leads to your question of how to properly overload the import function.

First I'd ask whether you actually need to overload import. If you just want to do some extra work in your module before anyone uses your code, you can do that at the end of your module, like this:

$ cat Foo.pm package Foo; require Exporter; our @ISA = qw( Exporter ); our @EXPORT_OK = qw( saySomething ); sub saySomething { print "Foo!\n"; } # Special package initialization stuff print "Special FOO.PM initialization complete!\n"; 1; $ cat T.pl #!env perl use lib '.'; use Foo qw( saySomething ); print "Begin\n"; saySomething(); print "End\n"; $ perl t.pl Special FOO.PM initialization complete! Begin Foo! End

The only time I can think of where you would need to overload import is if (a) import() doesn't do something that you need done, and (b) you're going to create other packages that rely on your package which need that extra behavior. If both of these are the case, I expect you'll need to look at the source code to Exporter and see what the import function does and how to not interfere with it. I've not done so, so I don't have much to offer you in that case. I did, however, look over the Exporter docs, though, and found that there's a section "Exporting Without Using Exporter's import Method" that may give you a starting point.

...roboticus

When your only tool is a hammer, all problems look like your thumb.

Replies are listed 'Best First'.
Re^2: Exporter. Correct way to override import?
by Veltro (Hermit) on May 05, 2018 at 08:27 UTC

    Thanks both Dave and roboticus,

    The thing that I actually tried to solve was slightly different, but I decided to simplify the question because I just knew the problem was how I was using the import function.

    What I was trying to do was:

    # Foo package Foo ; use strict ; use warnings ; require Exporter ; our @ISA = qw( Exporter ) ; our @EXPORT_OK = qw( saySomethingElse ) ; # sub import { # Foo->export_to_level( 1, @_ ) ; # } sub saySomethingElse { print "Good morning!\n" ; } 1 ;
    # Bar package Bar ; use strict ; use warnings ; use base qw( Foo ) ; 1 ;

    In the next code, I wanted both lines to work because I am sometimes using the module Foo and sometimes the module Bar. The 'use Bar...' line refused to work.

    # main use Bar qw ( saySomethingElse ) ; # use Foo qw ( saySomethingElse ) ; saySomethingElse() ;

    Now that I have the import function correct, I got this to work

    Thanks again to both of you! ++