[tpm] how to delete array entries en-passant

Fulko Hew fulko.hew at gmail.com
Wed Jun 30 09:11:33 PDT 2010


On Wed, Jun 30, 2010 at 11:41 AM, Shlomi Fish <shlomif at iglu.org.il> wrote:

> Hi Fulko,
>
> On Wednesday 30 Jun 2010 18:06:49 Fulko Hew wrote:
> > As the subject line asks...
> > what I'd like to do is something like
> >
> > foreach (@array) {
> >     if (condition) {
> >         splice @array, this_entry, 1;
> >         next;
> >     }
> >     do processing on this entry;
> > }
> >
> > @array now contains a sub-set of the original
> > that I can now further process
> >
>
> It's always a bad idea to modify the order of an array's elements while
> iterating over it using foreach. Don't do that.
>

OK, let me give you the specific example...
The array contains all of the lines of a file...
The foreach is used to loop over then, and 'take action' upon them.
But when I'm done I want all the empty lines stripped from the array ('just
because!')


> I should also note splicing an index out of the middle of an array is an
> O(N)
> operation where N is the number of elements in the array.
>

I know, thats why I was looking for a 'faster' technique.

I guess the alternative could be (shown simplified):

my @array;
while ($_ = <>) {
    next unless $_;      # skip empty lines
    push @array, $_;     # but remember non-empty lines
    process($_);
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/toronto-pm/attachments/20100630/dffd3821/attachment-0001.html>


More information about the toronto-pm mailing list