【问题标题】:Perl Can't locate object methodPerl 找不到对象方法
【发布时间】:2020-01-06 08:01:06
【问题描述】:

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

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

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

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

**

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!

我怀疑这很容易,但我希望有人可以帮助我。提前致谢

【问题讨论】:

    标签: perl


    【解决方案1】:

    直接的问题是你的代码中没有名为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');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-15
      • 2015-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-22
      相关资源
      最近更新 更多