0

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 ?

8
  • 2
    Try to put BEGIN {} around the sub def and move it before the use Mypackage statement Commented Apr 11, 2018 at 8:54
  • 2
    Your package declaration is wrong. Perl's keywords are case sensitive. It's package, not Package. Commented Apr 11, 2018 at 8:58
  • @Hakon, I get: Undefined subroutine &main::test not work. Commented Apr 11, 2018 at 9:07
  • 2
    Also, use should be lowercase, and Mypackage should have extension pm, not pl. Commented Apr 11, 2018 at 9:08
  • 2
    @Thenothing Ok, please update the question and show the new code. It works for me. Commented Apr 11, 2018 at 9:08

1 Answer 1

5

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;
Sign up to request clarification or add additional context in comments.

4 Comments

I really appreciate your help, is this possible to do in form of OOP ?, I want to call of subroutine in syntax of OO.
@Thenothing for an object oriented call, you need an object to call your method on. There's no object in this context, and your main namespace wouldn't typically be a class.
@Hakon, sorry but this aproach does not work with plackup program.psgi but if work with perl program.psgi, in plack I get Undefined subroutine &main::test
@Thenothing Sorry I am not familiar with plackup. Maybe you should post a new question showing the specific code you are using?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.