无法使用 Perl 中的 Exporter 模块导出方法
Not able to export methods using Exporter module in perl
我正在尝试使用 Exporter
perl 模块导出在我的自定义模块中编写的方法。下面是我的自定义模块 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;
下面是 ops_export.pl
使用 ops.pm
的脚本
#!/usr/bin/perl
use strict;
use warnings;
use ops;
my $num=add(1,2);
print "$num\n";
当我执行上面的脚本时,出现以下错误。
Undefined subroutine &main::add called at ops_export.pl line 8.
我不明白为什么我的脚本正在签入 &main
包,即使我已经使用 @EXPORT
在 ops.pm
中导出了 add
我哪里错了?
ops
是一个编译指示 already used by Perl。来自文档:
ops - Perl pragma to restrict unsafe operations when compiling
我不知道这到底是什么意思,但这就是问题所在。
将您的模块重命名为其他名称,最好像@simbabque 在评论中建议的那样使用大写字符,因为小写 "modules" 以某种方式保留用于编译指示(想想 warnings
或 strict
).
另外:调用您的 add
函数将不起作用,因为您混淆了 OO 代码和常规函数。您的 add
需要三个参数,而您只提供了两个(1
和 2
)。
编写 OO 模块时,您不应导出任何内容(甚至 new
),即:
package Oops;
use strict; use warnings;
use OtherModules;
# don't mention 'Export' at all
sub new {
...
}
sub add {
...
}
1;
然后在您的脚本中:
use strict; use warnings;
use Oops;
my $calculator = Oops->new();
my $result = $calculator->add(1, 2);
print $result, "\n"; # gives 3
我正在尝试使用 Exporter
perl 模块导出在我的自定义模块中编写的方法。下面是我的自定义模块 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;
下面是 ops_export.pl
使用 ops.pm
#!/usr/bin/perl
use strict;
use warnings;
use ops;
my $num=add(1,2);
print "$num\n";
当我执行上面的脚本时,出现以下错误。
Undefined subroutine &main::add called at ops_export.pl line 8.
我不明白为什么我的脚本正在签入 &main
包,即使我已经使用 @EXPORT
ops.pm
中导出了 add
我哪里错了?
ops
是一个编译指示 already used by Perl。来自文档:
ops - Perl pragma to restrict unsafe operations when compiling
我不知道这到底是什么意思,但这就是问题所在。
将您的模块重命名为其他名称,最好像@simbabque 在评论中建议的那样使用大写字符,因为小写 "modules" 以某种方式保留用于编译指示(想想 warnings
或 strict
).
另外:调用您的 add
函数将不起作用,因为您混淆了 OO 代码和常规函数。您的 add
需要三个参数,而您只提供了两个(1
和 2
)。
编写 OO 模块时,您不应导出任何内容(甚至 new
),即:
package Oops;
use strict; use warnings;
use OtherModules;
# don't mention 'Export' at all
sub new {
...
}
sub add {
...
}
1;
然后在您的脚本中:
use strict; use warnings;
use Oops;
my $calculator = Oops->new();
my $result = $calculator->add(1, 2);
print $result, "\n"; # gives 3