delete

delete EXPR

Given an expression that specifies a hash element, array element, hash slice, or array slice, deletes the specified element(s) from the hash or array. In the case of an array, if the array elements happen to be at the end, the size of the array will shrink to the highest element that tests true for exists() (or 0 if no such element exists).

Returns each element so deleted or the undefined value if there was no such element. Deleting from $ENV{} modifies the environment. Deleting from a hash tied to a DBM file deletes the entry from the DBM file. Deleting from a tied hash or array may not necessarily return anything.

Deleting an array element effectively returns that position of the array to its initial, uninitialized state. Subsequently testing for the same element with exists() will return false. Note that deleting array elements in the middle of an array will not shift the index of the ones after them down--use splice() for that. See /exists.

The following (inefficiently) deletes all the values of %HASH and @ARRAY:

    foreach $key (keys %HASH) {
	delete $HASH{$key};
    }
    foreach $index (0 .. $#ARRAY) {
	delete $ARRAY[$index];
    }

And so do these:

    delete @HASH{keys %HASH};
    delete @ARRAY[0 .. $#ARRAY];

But both of these are slower than just assigning the empty list or undefining %HASH or @ARRAY:

    %HASH = ();		# completely empty %HASH
    undef %HASH;	# forget %HASH ever existed
    @ARRAY = ();	# completely empty @ARRAY
    undef @ARRAY;	# forget @ARRAY ever existed

Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash element, array element, hash slice, or array slice lookup:

    delete $ref->[$x][$y]{$key};
    delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};
    delete $ref->[$x][$y][$index];
    delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];