1

I want to use a subroutine defined in a script B.pm(which I don't own) in my script A.pl. Since B.pm doesn't have a package pkg_B; header in it, all subroutines are imported when I add use B (); in A.pl. This results in Subroutine redefined warning when I try to run A.pl, since A.pl has a subroutine with the same name as that in B.pm. Is there a way I can isolate B.pm's namespace from A.pl without touching B.pm(since there are many other scripts blatantly consuming B.pm's subroutines without specifying scope)? My only solution seems to be renaming my subroutine, which I don't want to.

1
  • 3
    Re "Since B.pm doesn't have a package pkg_B; header in it" Well, there's the error. Commented Nov 11, 2015 at 17:40

1 Answer 1

5

... all subroutines are imported when I add use B (); in A.pl

The subroutines are not imported. They are defined in the namespace of your B.pm file. Since this file has no package name the namespace is main, i.e. the same namespace as A.pl is. And thus you have the conflict of two symbols with the name name inside the same namespace. What you could do is to include B.pm inside its own namespace, e.g.

{
     package Foo;
     do 'B.pm';  # defines sub foo
}

sub foo { ... }

foo(); # call local function
Foo::foo(); # call function from B.pm

Note that this is only a bad hack to work around bad code and you better should fix your code. And note also that you should not call your file/module B.pm/B because there is a core module with this name already.

Sign up to request clarification or add additional context in comments.

4 Comments

you better should fix your code You mean fix B.pm ?
@Jean: yes, use a proper namespace inside the module
Hmm.. B.pm is a legacy piece of code which I don't own.
If PHB forbids you from modifying the legacy code, and you don't want to wrap it in a package, you could always wrap your own competing code in a package...

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.