Suppose I have an array
my @a
and this array contains some elements that I want to get rid of. Further, I don't know which indices of the array contain the elements I want to expunge, and I want the final array I end up with to contain no empty indices--i.e. I want to ``shorten" the array by 1 everytime I expunge the contents of any of its indices. The way to do this that strikes me as obvious seems inelegant:
my @new_a; for my $i (0..$#a){ push (@new_a, $a[$i]) unless is_unwanted($a[$i]); } @a = @new_a; @new_a = ();
where is_unwanted is a sub that tests to find out if the contents of an index are of a sort I want to get rid of. Is there a way to do this without creating this extra @new_a array? A (naive) use of splice won't work, since splicing an array changes the identity of the indices with each call. E.g.
my @a = ("bob", "bob", "martha", "bob"); for my $i (0..$#a){ splice (@a, $i, 1) if $a[$i] =~ m/bob/; } #@a is now ("bob", "martha"), but I don't want any "bob"s; #also I get harassed about uniniatialized values when I use warnings
Thanks!

In reply to better array plucking? by young_stu

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.