这是我第一次使用perl(v5.28.1)。我收到错误消息:
'Can't locate object method "load" via stepReader (perhaps you forgot to load 'stepReader')'.
Run Code Online (Sandbox Code Playgroud)
当我在文件中打印某些内容时,它可以工作,但是以某种方式找不到我的方法。
我stepReader.pm在一个子目录中src
**
example.pm
use lib 'src/';
use stepReader;
@ISA = ('stepReader');
my $class = stepReader->load('assets/glasses.STEP');
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
输出:
Can't locate object method "load" via package "stepReader" (perhaps you forgot to load "stepReader"?) at example.pm line 6.
test if this works!
Run Code Online (Sandbox Code Playgroud)
我怀疑这很容易,但是我希望有人可以帮助我。提前致谢
直接的问题是stepReader您的代码中没有只调用类src::stepReader:
Run Code Online (Sandbox Code Playgroud)package src::stepReader;
也就是说,该函数称为src::stepReader::load,而不是stepReader::load。将包声明更改为:
package stepReader;
Run Code Online (Sandbox Code Playgroud)
同样,以小写字母开头的模块名称被非正式地保留给实用程序。对于普通模块,惯例是使用大写字母:
package StepReader;
Run Code Online (Sandbox Code Playgroud)
(并重命名StepReader.pm要匹配的文件)。
参数解包也坏了:
Run Code Online (Sandbox Code Playgroud)# Variable for file path my $filename = @_;
这会将@_数组置于标量上下文中,从而给出元素的数量。您要改为分配列表(在左侧带有括号),并且方法调用将调用方作为隐式的第一个参数传递:
my ($class, $filename) = @_;
...
return bless {}, $class;
Run Code Online (Sandbox Code Playgroud)
或者:
my $class = shift;
my ($filename) = @_;
Run Code Online (Sandbox Code Playgroud)
要么
my $class = shift;
my $filename = shift;
Run Code Online (Sandbox Code Playgroud)
您应该始终使用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');
Run Code Online (Sandbox Code Playgroud)