delete HASH
Perl's
delete() function is used to clear specific elements from hashes and lists, though it does not actually
remove the element. Using delete simply clears the
value of the element to an undefined state.
@myNames = ('jacob', 'alexander', 'ethan', 'andrew');
print "@myNames\n";
delete(@myNames[2]);
print "@myNames\n";
In the above example, we start with an array of names, and then delete the element at index 2 (in this case,
ethan). By printing the array after deleting the index, you'll see that a space for the element is still there, but the value is gone:
jacob alexander ethan andrew
jacob alexander andrew
The return value of the delete function is either the value of the last element deleted in a scalar context, or all of the values delete in a list context.
@myNames = ('jacob', 'alexander', 'ethan', 'andrew');
print "@myNames\n";
$result = delete(@myNames[2]);
print "@myNames\n";
print "$result\n";
In the above example,
$result will be
ethan. Let's look at the same example, but deleting from a hash:
%sampleHash = ('name' => 'Bob', 'phone' => '111-111-1111', 'cell' => '222-222-2222');
print %sampleHash;
print "\n";
$result = delete($sampleHash{'phone'});
print %sampleHash;
print "\n";
print "$result\n";
You'll see that
$result becomes the value of the phone key, and it is removed from the hash.
More Perl Quick Tips