Perl | delete() Function

Delete() in Perl is used to delete the specified keys and their associated values from a hash, or the specified elements in the case of an array. This operation works only on individual elements or slices.

Syntax: delete(LIST)

Parameters:
LIST which is to be deleted

Returns:
undef if the key does not exist otherwise it returns the value associated with the deleted key

Example 1: Implementing delete() on a Hash

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Initializing hash 
%hash1 = ('Geeks' => 45, 'for' => 30, 'Now' => 40); 
  
# To delete the List passed as parameter
$deleted_element = delete($hash1{'for'});
  
# Printing elements of Hash 
print "$hash1{'Geeks'}\n"
print "$hash1{'for'}\n"
print "$hash1{'Now'}\n"
  
# Printing the deleted element
print "Deleted element: $deleted_element";

chevron_right


Output:

45

40
Deleted element: 30

Example 2: Implementing delete() on an Array

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# Initializing array
@array1 = (10, 20, 30, 40, 50, 60); 
  
# To delete the array element at index 2
$deleted_element = delete(@array1[2]);
  
# Printing elements of Array 
print "Updated Array: @array1";
  
# Printing the deleted element
print "\nDeleted element: $deleted_element";

chevron_right


Output:

Updated Array: 10 20  40 50 60
Deleted element: 30


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.