user210757
user210757

Reputation: 7386

Perl - testing existence of key in hash reference that is member variable

I get the error "Not a HASH reference" with the following code. What is the proper way to test exists in a hash reference that's a member variable of a class?

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

Upvotes: 1

Views: 3559

Answers (2)

ikegami
ikegami

Reputation: 385725

$self->{_ht} is not a reference to a hash. It's a reference to a scalar. That scalar is a reference to a hash.

You want:

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

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

Or more likely:

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

if (exists $self->{_ht}->{$key})

Upvotes: 6

Greg Bacon
Greg Bacon

Reputation: 139451

In your constructor, you initialized $self->{_ht} to \{}, which is a reference to a hashref. Change it to

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

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

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

Upvotes: 6

Related Questions