2
votes

I am facing one issue with my perl code. I have created one package 'Welcome.pm' and using that in a script 'hello.pl'. But getting below error 'Undefined subroutine &main::First called at hello.pl line 6' I looked at other answers as well but still couldn't figure out what is wrong with code.

Can anyone please help?

perl module Welcome.pm

package Welcome;

use strict;
use warnings;
use base 'Exporter';
my @ISA = qw(Exporter);
my @EXPORT = qw(First);  

sub First{
print "welcome\n\n";
}


1;

perl script hello.pl

#!usr/bin/perl
use UsersModules::Welcome qw(First);
use strict;
use warnings;

First();
1

1 Answers

7
votes

The file name and the package name must tie up, so the statement

package UsersModules::Welcome

must appear in the file

UsersModules/Welcome.pm

The @ISA array needs to be a package variable (declared with our) instead of a lexical variable, but rather than manipulating it directly it is best to

use parent 'Exporter';

However, the best choice is to import the import subroutine from Exporter instead of inheriting it, so you can write just

use Exporter 'import';

The @EXPORT array must also be a package variable

Like this

package UsersModules::Welcome;

use strict;
use warnings;

use Exporter 'import';

our @EXPORT = qw/ First /;

sub First{
    print "welcome\n\n";
}


1;

If you want to import a subroutine named in the @EXPORT list, then there is no need to mention it in your use statement. (If you had put it in the @EXPORT_OK list then you would have to name it in the use statement.)

Together with the above module, this main program works fine

#!usr/bin/perl

use strict;
use warnings;

use UsersModules::Welcome;

First();

output

welcome