Perl - 测试作为成员变量的哈希引用中键的存在

use*_*757 0 perl hash exists

我使用以下代码获得错误"Not a HASH reference".测试的正确方法是什么?哈希引用是类的成员变量?

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')
Run Code Online (Sandbox Code Playgroud)

Gre*_*con 5

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

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

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

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


ike*_*ami 5

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

你要:

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

if (exists ${ $self->{_ht} }->{$key})  # Scalar deref added
Run Code Online (Sandbox Code Playgroud)

或者更有可能:

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

if (exists $self->{_ht}->{$key})
Run Code Online (Sandbox Code Playgroud)