http://www.perlmonks.org?node_id=474796


in reply to Pop/shift/delete on array

The push and pop functions act at the high-index end of an array. Shift and unshift act on the low-index end.

The delete operator doesn't really belong in the list. It removes pairs from a hash, but on an array it only undefines the value of an element. For arrays, splice is the corresponding operator.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: Pop/shift/delete on array
by betterworld (Curate) on Jul 14, 2005 at 16:07 UTC
    The delete operator doesn't really belong in the list. It removes pairs from a hash, but on an array it only undefines the value of an element.
    This is not quite true. If you delete the last element of an array, the array will actually shrink:
    my @array = qw/tiger dog cat/; delete $array[2]; print scalar @array; # Output is 2
    You can even have it funnier:
    my @array = qw/tiger dog cat/; delete $array[1]; print scalar @array; # Output is 3 delete $array[2]; print scalar @array; # Output is 1
    However, this seemingly equivalent code does behave weird:
    my @array = qw/tiger dog cat/; delete $array[1]; print scalar @array; # Output is 3 splice @array, 2; print scalar @array; # Output is 2
Re^2: Pop/shift/delete on array
by revdiablo (Prior) on Jul 14, 2005 at 16:39 UTC
    on an array it only undefines the value of an element

    Actually, it does a bit more than "only" undefining the value. I'm not sure how useful this behavior is, but it's not quite the same as simply setting the value to undef. Here's a code snippet that demonstrates:

    $ perl -MData::Dumper -le ' @array = (1 .. 3); delete $array[1]; print Dumper \@array; delete $array[2]; print Dumper \@array;'

    When run, it outputs the following:

    $VAR1 = [ 1, undef, 3 ]; $VAR1 = [ 1 ];

    We see that the first delete call does indeed appear to simply set the value to undef, but when we delete again, it demonstrates the difference.

    Update: betterworld beat me to it, by a pretty large margin. That'll teach me not to reload before replying. :-)