-- Perl 5.8.8 documentation --
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 a list with the same number of elements as the number of elements for which deletion was attempted. Each element of that list consists of either the value of the element deleted, or the undefined value. In scalar context, this means that you get the value of the last element deleted (or the undefined value if that element did not exist).

        %hash = (foo => 11, bar => 22, baz => 33);
        $scalar = delete $hash{foo};             # $scalar is 11
        $scalar = delete @hash{qw(foo bar)};     # $scalar is 22
        @array  = delete @hash{qw(foo bar baz)}; # @array  is (undef,undef,33)

    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. Also, deleting array elements in the middle of an array will not shift the index of the elements 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];