1

我收到以下代码的错误“不是 HASH 引用”。测试作为类成员变量的哈希引用中存在的正确方法是什么?

package TestClass;

sub new {
    my ($class) = @_;

    my $self = {
        _ht => \{}
    };

    bless $self, $class;
    return $self;
}

sub itemExists {
    my ($self, $key) = @_;
    my $itemExists = 0;

    if(exists $self->{_ht}->{$key}) { # ERROR HERE: Not a HASH reference
        $itemExists = 1;
    }

    return $itemExists;
}

1;

# ------------------------------------------
package Main;

my $t = new TestClass();
$t->itemExists('A')
4

2 回答 2

6

在您的构造函数中,您初始化$self->{_ht}\{},这是对 hashref 的引用。将其更改为

sub new {
    my ($class) = @_;

    my $self = {
        _ht => {}   # backslash removed
    };

    bless $self, $class;
    return $self;
}
于 2012-05-23T19:58:47.403 回答
6

$self->{_ht}不是对哈希的引用。它是对标量的引用。该标量是对哈希的引用。

你要:

my $self = {
    _ht => \{},
};

if (exists ${ $self->{_ht} }->{$key})  # Scalar deref added

或者更有可能:

my $self = {
    _ht => {},  # Ref to scalar removed
};

if (exists $self->{_ht}->{$key})
于 2012-05-23T19:59:11.650 回答