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

11.6k views Asked by At

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.

3

There are 3 answers

3
Sobrique On BEST ANSWER

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.

1
Raghuveer On

Undefined error could be because your B.PM is not able to find A.PM. Can you try using

use FindBin;
use lib "$FindBin::Bin/../lib";

or directly using use lib "$folder containing A.pm"

Also, I am not clear where are you getting undefined. In your perl script or in your B.PM module ?

0
Matthew Lock On

I just wanted to directly call a sub (glob) from a perl module (File::Glob::Windows) without import the sub glob as it was clashing with Moose with the error "overwriting a locally defined function with an accessor".

This pointed me in the right direction: https://www.perlmonks.org/?node_id=623567

use File::Glob::Windows qw();   # Hide everything

...

File::Glob::Windows::glob(...); # Access sub explicitly