PERL: How to remove an element from hash or array?

In order to remove an element from the array or hash, we have to use the delete keyword on perl. Using the delete keyword on the key of the hash or array (numeric keyed hash), we can delete elements of a hash or array.

Example for deleting an element from a hash

The following code deletes the key 'a' from the hash
%hash
. #!/usr/bin/perl $, = "\n"; # Fields separator my %hash = ( 'a' => 'aaa', 'b' => 'bbb', 'c' => 'ccc', ); print %hash; delete $hash{a}; #key value pair 'a' => 'aaa' would be deleted print %hash;

Example for deleting an element from an array

The code below deletes an index from an array. #!/usr/bin/perl $, = "\n"; # Fields separator my @array= ('a','b','c','d','e'); print @array; delete $array[0]; #value a would be deleted print @array;

Example for deleting an element from a hash By Value

#!/usr/bin/perl $, = "\n"; # Fields separator my %hash = ( 'a' => 'aaa', 'b' => 'bbb', 'c' => 'ccc', ); print %hash; map {delete $hash{$_} if $_ eq 'bbb' } %hash; #key value pair 'b' => 'bbb' would be deleted print %hash;

Example for deleting an element from an array By Value

The code below deletes a given value from an array. #!/usr/bin/perl $, = "\n"; # Fields separator my @array= ('a','b','c','d','e'); print @array; map {delete $array[$_] if $_ eq 'c' } @array; #All 'c' would be deleted. print @array; 29 Mar, 2010
Comments (0)
You may also like
Tags
On Facebook
Email Newsletter