Modules

  • ABCDE
  • FGHIL
  • MNOPS
  • TUX

Tools

delete

Perl 5 version 8.8 documentation
Recently read

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).

    1. %hash = (foo => 11, bar => 22, baz => 33);
    2. $scalar = delete $hash{foo}; # $scalar is 11
    3. $scalar = delete @hash{qw(foo bar)}; # $scalar is 22
    4. @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:

    1. foreach $key (keys %HASH) {
    2. delete $HASH{$key};
    3. }
    4. foreach $index (0 .. $#ARRAY) {
    5. delete $ARRAY[$index];
    6. }

    And so do these:

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

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

    1. %HASH = (); # completely empty %HASH
    2. undef %HASH; # forget %HASH ever existed
    3. @ARRAY = (); # completely empty @ARRAY
    4. 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:

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