8

This is a module math.pm with 2 basic functions add and multiply:

package Math;
use strict;
use warnings;
use Exporter qw(import);
our @EXPORT_OK = qw(add multiply); 

sub add {
my ($x, $y) = @_;
return $x + $y;
}

sub multiply {
my ($x, $y) = @_;
return $x * $y;
}

1;

This is script script.pl that call the add function:

#!/usr/bin/perl
use strict;
use warnings;

use Math qw(add);
print add(19, 23);

It gives an error:

can't locate math.pm in @INC <@INC contain: C:/perl/site/lib C:/perl/lib .> at C:\programs\script.pl line 5. BEGIN failed--compilation aborted at C:\programs\script.pl line 5.

How to solve this problem?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
abc
  • 91
  • 1
  • 1
  • 3
  • 1
    What is the question? What is the problem? – serenesat Jun 05 '15 at 05:57
  • hey @serenesat prob is in this code is not working and giving such kind of error – abc Jun 05 '15 at 06:25
  • For me its working fine. If you put both program on same path. It should work. – serenesat Jun 05 '15 at 06:51
  • don't knw what was wrong when m running this program – abc Jun 05 '15 at 06:56
  • 2
    In the error message it says `math.pm` and your code shows `package Math;` (in file called `Math.pm`) - you have to use the correct capitalization. Check the file name of your module and your script `use math;` will cause the error message you have shown. – dgw Jun 05 '15 at 07:19
  • possible duplicate of [How do I include a Perl module that's in a different directory?](http://stackoverflow.com/questions/841785/how-do-i-include-a-perl-module-thats-in-a-different-directory) – serenesat Jun 05 '15 at 07:28
  • FYI https://perlmaven.com/how-to-create-a-perl-module-for-code-reuse – gihan-maduranga Jun 24 '17 at 07:08

2 Answers2

11

use lib

Adding a use lib statement to the script will add the directory to @INC for that specific script. Regardless who and in what environment runs it.

You just have to make sure to have the use lib statement before trying to load the module:

use lib '/path/to/module';
use Math qw(add);

For more details to set @INC look at this:

How do I include a Perl module that's in a different directory

Community
  • 1
  • 1
serenesat
  • 4,611
  • 10
  • 37
  • 53
0

Add the following to script.pl before use Math ...;:

use FindBin qw( $RealBin );
use lib $RealBin;

If script.pl and math.pm aren't in the same directory, adjust accordingly.

Also, you might have problems if the file is named math.pm and you use use Math; and package Math;. It would be best to rename the file so the spelling is consistent.

ren math.pm Math.pm
ikegami
  • 367,544
  • 15
  • 269
  • 518