不是Perl类中的代码引用

Kev*_*vin -1 oop perl

我很难过.我是Perl的新手,在阅读了一些文章后,我仍然无法想出这个.这是一个非常小的课程.

package Haha;

sub new {
    $class = shift;

    $self = {
        path => shift
    };

    bless $self, $class;

    return $self;
}

sub setPath {
    my ($self, $new_path) = shift;
    $self->(path) = $new_path if defined $new_path;
    return $self->(path);
}

sub getPath {
    my $self = shift;
    return $self->(path);
}

1;
Run Code Online (Sandbox Code Playgroud)

我用它是这样的:

use lib 'lib';
use Haha;

my $new_excel = new Haha("sample path");

print $new_excel->getPath() ;

<>;
Run Code Online (Sandbox Code Playgroud)

Haha第23行引发了"Not a code reference"错误.这条线说return $self->(path);

Dav*_*oss 9

你的类(像大多数Perl类一样)是在哈希上实现的.在构造函数中创建新对象时,可以这样做:

sub new {
    $class = shift;

    $self = {
        path => shift
    };

    bless $self, $class;

    return $self;
}
Run Code Online (Sandbox Code Playgroud)

该行$self = { ... }创建一个匿名哈希并存储对该哈希的引用$self.所以,$self是一个哈希引用.这意味着您应该使用哈希语法访问其内容.所以你的访问器和mutator方法都是错误的.

sub setPath {
    my ($self, $new_path) = shift;
    $self->(path) = $new_path if defined $new_path;
    return $self->(path);
}
Run Code Online (Sandbox Code Playgroud)

您使用括号而不是大括号来访问path哈希值.这条线:

$self->(path) = $new_path if defined $new_path;
Run Code Online (Sandbox Code Playgroud)

应该:

# Note: braces, not parentheses
$self->{path} = $new_path if defined $new_path;
Run Code Online (Sandbox Code Playgroud)

和行:

return $self->(path);
Run Code Online (Sandbox Code Playgroud)

应该:

# Note: braces, not parentheses
return $self->{path};
Run Code Online (Sandbox Code Playgroud)

你需要做一个类似的修复getPath().

不幸的是,语法$reference->($value)完全有效.这意味着"调用你有引用的子程序$reference,传递它$value".但是,当然,这需要$reference包含子例程引用,而不是哈希引用.

其他一些建议.

  1. 永远use strictuse warnings.
  2. 间接对象​​表示法($new_excel = new Haha("sample path"))可能会在某些时候刻录你.请$new_excel = Haha->new("sample path")改用.
  3. 你的生产线my ($self, $new_path) = shift不符合你的想法.你想要的my ($self, $new_path) = @_.