这是我第一次使用 perl (v5.28.1)。我收到错误:
'Can't locate object method "load" via stepReader (perhaps you forgot to load 'stepReader')'.
当我在文件中打印某些内容时,它可以工作,但不知何故找不到我的方法。
我有
stepReader.pm
在名为 src
的子目录中**
示例.pm
use lib 'src/';
use stepReader;
@ISA = ('stepReader');
my $class = stepReader->load('assets/glasses.STEP');
stepReader.pm
package src::stepReader;
use strict;
use warnings;
sub load {
# Variable for file path
my $filename = @_;
# Open my file
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
# Print the file!
while (my $row = <$fh>) {
chomp $row;
print "$row\n";
}
return bless {}, shift;
}
print "test if this works!";
1;
输出:
Can't locate object method "load" via package "stepReader" (perhaps you forgot to load "stepReader"?) at example.pm line 6.
test if this works!
我怀疑这很容易,但我希望有人能帮助我。提前致谢
最佳答案
直接的问题是没有名为 stepReader
的类。在您的代码中,只有 src::stepReader
:
package src::stepReader;
即函数调用
src::stepReader::load
,而不是 stepReader::load
.将包声明更改为:package stepReader;
此外,以小写字母开头的模块名称非正式地保留给 pragmata。对于普通模块,约定是使用大写字母:
package StepReader;
(并重命名文件
StepReader.pm
以匹配)。参数解包也被破坏:
# Variable for file path my $filename = @_;
这使得
@_
标量上下文中的数组,给出元素的数量。您需要列表赋值(左侧有括号),并且方法调用将调用者作为隐式的第一个参数传递: my ($class, $filename) = @_;
...
return bless {}, $class;
或者:
my $class = shift;
my ($filename) = @_;
或者
my $class = shift;
my $filename = shift;
您应该始终以
use strict; use warnings;
开始您的文件。或等效的。 example.pm
目前缺少它:use strict;
use warnings;
use lib 'src';
use StepReader;
# This line is not needed, but if it were:
# our @ISA = ('StepReader');
关于Perl 找不到对象方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57771227/