尝试在其他perl文件中调用子例程(在用户定义的模块中定义)时,获取错误的参数值
#moduleName.pm
package PackageName::moduleName;
use strict;
use warnings;
use base 'Exporter';
sub callMe{
my($readArg)=(@_);
print $readArg;
}
#test.pl
use strict;
use warnings;
use FindBin; # locate this script
use lib 'path to parent directory'; # use the parent directory
use PackageName::moduleName;
if( my $temp=PackageName::moduleName->callMe("test")){
print" True : $temp\n";
}
该函数将$ temp的值打印为:PackageName :: moduleName
无法弄清楚原因。
P.S。我必须在调用子程序时保持相同的约定
答案 0 :(得分:3)
您正在使用null
将函数作为类方法调用。在这种情况下,由于箭头Foo::Bar->frobnicate(@args)
:
->
,请找到包(例如blessed
是包$q
)CGI
)Foo::Bar
)现在看起来像这样:
frobnicate
在frobnicate,你必须处理:
Foo::Bar::frobnicate('Foo::Bar', @args);
通常在sub frobnicate {
my ($class, @args) = @_;
# ...
}
中完成,最有可能使用类方法。
如果您不想处理它,请直接在其命名空间中调用sub,而不是使用箭头符号。
new
答案 1 :(得分:1)
由于您通过->
调用它的方式。
执行此操作时,perl会传递额外的参数,因此您可以创建一个构造函数(new
)。
E.g。
my $thing = Package::Module -> new();
传递的第一个参数是类,因此您可以将其用于bless
。看到:
perlootut
E.g。
sub new {
my ( $class, @args ) = @_;
my $self = {};
bless ( $self, $class );
}
当您调用实例化对象时,这也适用:
$thing -> do_something();
它将对$self
的引用作为第一个参数传递。
sub do_something {
my ( $self, @args ) = @_;
print "Got args of @args\n";
$self -> {firstarg} = shift ( @args );
}
如果你想这样做,请尝试改为:
PackageName::ModuleName::callMe("test");