sid_com
sid_com

Reputation: 25107

Why do I get the error-message "Undefined subroutine" when calling a function from a module?

I have a module named Helpers.pm:

use warnings;
use 5.012;

package Helpers;
use Exporter qw(import);
our @EXPORT_OK = qw(my_function);

sub my_function {
    return { one => 1, two => 2 };
}

1;

an call it in the script:

#!/usr/bin/env perl
use warnings;
use 5.012;
use Data::Dumper;
use FindBin qw($RealBin);

use lib $RealBin;
use Helpers qw(my_function);

my $ref = my_function();
say Dumper $ref;

and I get no error-messages. But when I put the module in the directory TestDir an modify the script like this:

#!/usr/bin/env perl
use warnings;
use 5.012;
use Data::Dumper;
use FindBin qw($RealBin);

use lib $RealBin;
use TestDir::Helpers qw(my_function);

my $ref = my_function();
say Dumper $ref;

I get this error-message:

Undefined subroutine &main::my_function called at ./perl.pl line 10.

Why do I get this error-message?

Upvotes: 9

Views: 23399

Answers (2)

user149341
user149341

Reputation:

You probably forgot to change the package declaration from

package Helpers;

to:

package TestDir::Helpers;

Upvotes: 14

Dyno Fu
Dyno Fu

Reputation: 9044

i think it is because it cannot find your module in lib path, http://perldoc.perl.org/lib.html.

use lib 'TestDir';
use Helpers qw(my_function);

Upvotes: 3

Related Questions