Perl找不到对象方法

时间:2019-09-03 11:53:00

标签: perl

这是我第一次使用perl(v5.28.1)。我收到错误消息:

'Can't locate object method "load" via stepReader (perhaps you forgot to load 'stepReader')'. 

当我在文件中打印某些内容时,它可以工作,但是以某种方式找不到我的方法。

我在名为stepReader.pm的子目录中有src

**

example.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!

我怀疑这很容易,但是我希望有人可以帮助我。预先感谢

1 个答案:

答案 0 :(得分:7)

直接的问题是您的代码中没有名为stepReader的类,只有src::stepReader

package src::stepReader;

也就是说,该函数称为src::stepReader::load,而不是stepReader::load。将软件包声明更改为:

package stepReader;

此外,以小写字母开头的模块名称被非正式地保留给实用程序。对于普通模块,惯例是使用大写字母:

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');