How to delete some hash entries in Perl

Overview

The delete() method in Perl is used to delete the specified keys along with their associated value from a hash.

Syntax

The syntax of the delete() method is given below:

delete(hash(key))

Parameters

hash: This is the hash instance we want to delete some entries from.

key: This is the key that gets deleted along with its corresponding value.

Return value

The value returned is the value of the key that was deleted.

Code example

# create a Hash value
%hash1 = ("Google" => "G",
"Netflix" => "N",
"Amazon" => "A",
"Apple" => "A",
"Meta" => "M"
);
# delete some entries
$deletedValue1 = delete($hash1{"Google"});
$deletedValue2 = delete($hash1{"Meta"});
# print deleted elements
print "$deletedValue1\n";
print "$deletedValue2";

Code explanation

  • Line 2: We create a hash value.
  • Lines 10–11: We delete some entries from the hash we created, using the delete method.
  • Lines 14–15: We print the deleted elements to the console.

Free Resources