Perl presents arrays as dynamic but not sparse. As soon as you access element n, all the elements 0 .. n - 1 pop into existence with the value of undef if they didn't exist already. Deleting the contents of elements from the middle of an array doesn't change its length.

However, under the hood things are a little more complicated. Consider:

my @array; $array[4] = 0; print " Set element 4: last at $#array\n"; $array[2] = undef; delete $array[4]; print "Delete element 4: last at $#array\n"; delete $array[2]; print "Delete element 2: last at $#array\n";

Prints:

Set element 4: last at 4 Delete element 4: last at 2 Delete element 2: last at -1

so Perl differentiates between array elements that have been assigned to (even if the assignment was undef - that is, the element exists) and unassigned elements (the element doesn't 'exist'). Perl truncates an array back to the last element that exists when element [-1] is deleted. Otherwise, delete simply makes an array element "unassigned" (it doesn't exist any more).

If you want to remove the elements without leaving holes you could use splice or assign a slice that is the complement of the elements you want to remove:

use strict; use warnings; use strict; use Data::Dump ('dump'); my $listref = ['a','b','c','d','e']; @$listref = @{$listref}[0, 2, 4]; print "@$listref\n";

Perl reduces RSI - it saves typing

In reply to Re: delete array element from array ref by GrandFather
in thread delete array element from array ref by llancet

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.