Perl Programming/Keywords/delete

Previous: defined Keywords Next: DESTROY

The delete keywordEdit

The delete command deletes a slice of a hash, if an EXPRESSION is given that specifies elements of a hash. After deletion, exists() no more returns true for this element/these elements. Setting a hash element to undef does not remove its key, but the delete command does.

If it is called in list context, it returns the value(s) deleted. The returned list's length is equal to the original one with undefs in place of the deleted items. If called in scalar context, the last deleted value is returned.

delete can also be used for arrays and array slices with a less straightforward behaviour. In this case, although exists() returns also false for deleted items, their indices will never change. To make the indices change, shift()() or splice() has to be used.

WARNING: Calling delete on array values is deprecated and will probably be removed in a future version.




use 5.10.0;

%hash = (foo => 11, bar => 22, baz => 33);

for (($key, $element) = each %hash) {
  print "key => " . $key . " " . $element . "\n";

say 'delete $hash{foo}';
$scalar = delete $hash{foo}; # $scalar is 11

print $scalar . "\n";
$scalar = delete @hash{qw(foo bar)}; # $scalar is 22

print $scalar . "\n";
@array = delete @hash{qw(foo baz)}; # @array is (undef, 33)

say '@array = delete @hash{qw(foo baz)}';
for ($element = each @array) {
 print $element . "\n";
key => bar 22
key => bar 22
delete $hash{foo}
@array = delete @hash{qw(foo baz)}

See alsoEdit

Previous: defined Keywords Next: DESTROY