Search code examples
perlperl-module

How to call a subroutine from one perl module to another perl module?


I have a perl file which makes use of two perl modules A.pm , B.pm.

But in B.pm I need to call a subroutine of A.pm. Even if I give use in A.pm and try to use it I am still getting undefined error.

Any help on this greatly appreciated.


Solution

  • There's two elements - first is finding the module. Perl has a 'library' path that you can find by:

    print join ( "\n", @INC ); 
    

    This is the places where it looks. It will also check the current working directory, but it's a little bit more difficult using a run time relative path - you need to use the FindBin module for that.

    The second element is importing and exporting the subroutine. By default, if you use A; you won't import everything into your local name space because... you don't want to accidentally override one of your internal functions. That way lies madness.

    So you either:

    use A qw ( somefunction ); 
    

    Which will 'pull in' that function and define it in your local namespace. The exact behavor of these things can be modified via Exporter and setting @EXPORT and @EXPORT_OK.

    Or refer to it by the 'package path'.

    A::somefunction(@arguments);
    

    This also works for variables, although you will have to scope them with our rather than my.