Search code examples
perlnamespacespackagesubroutine

Perl - Call subroutine of main namespace from package


program.pl

Use Mypackage;

sub test{

print "from test";

}

Mypackage.pl

Package Mypackage;

::test();

This return nothing.

I see several threads about call subroutine in namespace from package, but I want to do the contrary

Print a subroutine in package from main namespace (program.pl)

is this possible ?


Solution

  • The statement use Mypackage is equivalent to

    BEGIN { require Mypackage; Mypackage->import( ); }
    

    So we see that the Mypackage is executed before the execution of the main program (since it is in a BEGIN block). See this answer for more information an another example. Hence the sub test() in the main program is not yet defined at this time. To make it work, we need to have it defined when Mypackage is run. One way to do that is to put it in a BEGIN block before the use Mypackage statement in the main program.

    BEGIN {
        sub test{
            print "from test\n";
        }
    }    
    use Mypackage;