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

I *think* I know why this is going on, but I would like someone smarter than me to explain it. I have spent some time reading documentation and did not find anything that explained this exact scenario.

Consider... Executing this code:
# Main script require 'TEST2.pm'; require 'TEST.pm'; test_sub();
produces the error "Undefined subroutine &main::test_sub called..."

The subroutine test_sub lives in the TEST package within TEST.pm, and is exported:
# TEST.pm *test_sub = *TEST::test_sub; package TEST; sub test_sub { print "Hello, world!\n"; }
and the contents of TEST2.pm:
# TEST2.pm package TEST2; require 'TEST.pm'; return 1;

So the main script requires TEST2.pm, which requires TEST.pm from within the TEST2 package. Then the main script requires TEST.pm, which is responsible for exporting the test_sub() subroutine. But it does not work. If I reverse the two require's in the main script, the call to test_sub() will work, but calling it from TEST2 will not work. I am under the impression that the first time require is called for TEST.pm (from the TEST2 package in TEST2.pm), test_sub() is exported to TEST2. When the main script then attempts to require TEST.pm, it is skipped because it has already been require'd. This means the main script cannot find test_sub() (unless the call to it is fully-qualified.) Is this the right reason for this behavior, or is something else going on? And is there any way to get the test_sub() subroutine to be recognizable from both the main script and the TEST2 package, without using a fully-qualified call?
  • Comment on Requiring libraries that export subroutines, and are required by other libraries... Exported subs cannot be found?
  • Select or Download Code

Replies are listed 'Best First'.
Re: Requiring libraries that export subroutines, and are required by other libraries... Exported subs cannot be found?
by ikegami (Patriarch) on Aug 08, 2008 at 02:03 UTC

    it is skipped because it has already been require'd.

    Exactly. Modules are only executed the first time they are required.

    That's the case for use as well, but it also calls the module's import method (if it has one). This is where your code belongs, and the code you need is provided by Exporter already.

    # TEST.pm package TEST; BEGIN { our @EXPORT_OK = qw( test_sub ); our @ISA = qw( Exporter ); require Exporter; } sub test_sub { print "Hello, world!\n"; }
    # TEST2.pm package TEST2; use TEST qw( test_sub ); 1;
    # Main script use TEST2; use TEST qw( test_sub ); test_sub();