4

I have integrate sample function in perl. Everything working fine but i am not able to connect Perl module package file(.pm)

Please review below code

sample.pl

#!/usr/bin/perl

 use strict;
 use warnings;
 use Sample;
print Sample->test_function();

Sample.pm

 package Sample;

  sub  test_function
  {

  return 'Welcome';

  }

Once after run the sample.pl file. It's return the error "Can't locate Sample.pm " but the package file availale in same folder.

VinothRaja
  • 1,405
  • 10
  • 21

2 Answers2

3

The reason of the issue is installed perl module location could not found . add the below line your sample.pl file

 use strict;
 use warnings;

 use Cwd qw( abs_path );
 use File::Basename qw( dirname );
 use lib dirname(abs_path($0));


 use Sample;
 print Sample->test_function();
VinothRaja
  • 1,405
  • 10
  • 21
VRB
  • 186
  • 14
3

First of all, your Sample.pm file must finish returning a true value. The common way to do that is appending 1; and the end of that file.

package Sample;
use strict;
use warnings;
sub  test_function {
   return 'Welcome';
}
1;

After Perl 5.26, current directory was removed from @INC. There are several ways to deal with this. For example, you can use the -I option when running the script:

perl -I. sample.pl

For a more deeper lecture on how to deal with @INC, please read this SO post.

Miguel Prz
  • 13,718
  • 29
  • 42
  • It doesn't make sense to force the script's invoker to provide that information. – ikegami Sep 22 '18 at 14:28
  • `-I ...` doesn't add arch dirs, so it doesn't always work. `-Mlib=...` should be used instead to get build-specific components. – ikegami Sep 22 '18 at 14:28