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

My problem is easier to show than explain. I have three files:

The main script:

# main.pl use Bar; use Foo; Bar("Called from main"); &Foo();
And two secondary scripts:
# Foo.pm package Foo; use Exporter; @ISA = 'Exporter'; @EXPORT = qw(Foo); use strict; sub Foo { Bar("Called from Foo"); } 1; # Bar.pm package Bar; use Exporter; @ISA = 'Exporter'; @EXPORT = qw(Bar); use strict; sub Bar { print "$_[0]\n"; } 1;
If I run them, I get this output:
Called from main Undefined subroutine &Foo::Bar called at Foo.pm line 7
Inserting a use Bar; within Foo clears up the problem. But since main already uses Bar, shouldn't Foo pick that up as well? What am I missing?

---
A fair fight is a sign of poor planning.

Replies are listed 'Best First'.
Re: "use" inheritance
by bart (Canon) on Nov 18, 2003 at 23:42 UTC
    You're missing the import.

    use actually does two things:

    1. require the module file
    2. call the import class method from the package of the module

    In order for perl to recognize your "imported" sub Bar in Foo, it needs to be imported into Foo! And by not use'ing Bar inside Foo, you not only skip the (indeed not strictly necessary) use, but also the import!

    There's noting wrong with using Bar twice. The require will be called only once, but then, Bar would indeed be imported both into main::, and into Foo::. Just like you want it.

    Or you could use fully qualified names. I'd go for the double import.

Re: "use" inheritance
by castaway (Parson) on Nov 18, 2003 at 23:38 UTC
    No, because 'use' (which calls 'import' in the module being 'used'), only imports the exported subs into the current namepsace, thus, main gets them, and Foo does not.

    C.