Reputation: 78
I'm trying to export the methods written in my custom module using Exporter
perl module. Below is my custom module ops.pm
use strict;
use warnings;
use Exporter;
package ops;
our @ISA= qw/Exporter/;
our @EXPORT=qw/add/;
our @EXPORT_OK=qw/mutliply/;
sub new
{
my $class=shift;
my $self={};
bless($self,$class);
return $self;
}
sub add
{
my $self=shift;
my $num1=shift;
my $num2=shift;
return $num1+$num2;
}
sub mutliply
{
my $self=shift;
my $num1=shift;
my $num2=shift;
return $num1*$num2;
}
1;
Below is the script ops_export.pl
using ops.pm
#!/usr/bin/perl
use strict;
use warnings;
use ops;
my $num=add(1,2);
print "$num\n";
when i execute the above script i'm getting below error.
Undefined subroutine &main::add called at ops_export.pl line 8.
I'm not getting why my script is checking in &main
package even though i have exported the add
in ops.pm
using @EXPORT
Where am i going wrong?
Upvotes: 1
Views: 244
Reputation: 5730
ops
is a pragma already used by Perl. From the docs:
ops - Perl pragma to restrict unsafe operations when compiling
I don't know what that actually means but that's the issue here.
Rename your module to something else, preferably something with uppercase characters as @simbabque suggests in a comment, because lowercase "modules" are somehow reserved for pragmas (think of warnings
or strict
).
Also: Calling your add
function won't work because you mix up OO code and regular functions. Your add
expects three parameters and you supply only two (1
and 2
).
When writing OO modules you shouldn't export anything (not even new
), i.e.:
package Oops;
use strict; use warnings;
use OtherModules;
# don't mention 'Export' at all
sub new {
...
}
sub add {
...
}
1;
And then in your scripts:
use strict; use warnings;
use Oops;
my $calculator = Oops->new();
my $result = $calculator->add(1, 2);
print $result, "\n"; # gives 3
Upvotes: 3