1. Home
  2. Computing & Technology
  3. Perl

Perl delete() function - Quick Tutorial
How to use the delete() function

From About.com

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
Explore Perl
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Perl
  4. Programming Perl
  5. Perl delete function reference - learn how to use Perl's delete() function in this quick tutorial.

©2009 About.com, a part of The New York Times Company.

All rights reserved.