Nabou
Nabou

Reputation: 549

Deleting key/value pairs from perl result in Global symbol requires explicit package name error

I am trying to delete certain key/value pairs from a hash, but I get the Global symbol requires explicit package name exception and I don't know how to debug this. I read up on some solutions, but none of them seem to work. So the hash is declared in this fashion:

my $hash = foo();

then I go through the hash using this line of code:

while (my ($key, $value) = each %$hash)

and in the block I select values I don't want and store the keys for these values in an array that was declared like this (before the loop of course):

my @keysArray = ();

I then access the array to retrieve the keys using this code so I can delete them from the hash:

for my $key (@keysArray){
    delete $hash{$key};# this line of code is causing the problem
}

The last line that I wrote is the one causing the Global symbol "%hash" requires explicit package name exception.

Any fixes or am I doing something wrong here.

P.S. I changed the variable names and removed other internal code, but the format is the same.

Help please! Thanks.

Upvotes: 0

Views: 2140

Answers (3)

zgpmax
zgpmax

Reputation: 2847

Your (repaired) code:

for my $key (@keysArray) {
    delete $hash->{$key};
}

can be shortened to

for my $key (@keysArray) {
    delete $$hash{$key};
}

or simply

delete @$hash{@keysArray};

Upvotes: 1

hobbs
hobbs

Reputation: 240010

delete $hash{$key} deletes an entry from %hash. There is no %hash. Instead you want to write delete $hash->{$key}, which deletes an entry from %$hash.

I suggest perldoc perlreftut for answering all of your questions about references and how to use them.

Upvotes: 9

CanSpice
CanSpice

Reputation: 35808

You've declared $hash (a scalar reference to a hash) but not %hash (a hash). Try doing delete $hash->{$key} instead.

Upvotes: 3

Related Questions