[tpm] how to delete array entries en-passant

Shaun Fryer sfryer at sourcery.ca
Wed Jun 30 09:25:44 PDT 2010


@array = grep {!/^\s*\z/} @array; # strip empty (or whitespace only) lines
--
Shaun Fryer

On Wed, Jun 30, 2010 at 12:11 PM, Fulko Hew <fulko.hew at gmail.com> wrote:
>
>
> 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($_);
> }
>
>
> _______________________________________________
> toronto-pm mailing list
> toronto-pm at pm.org
> http://mail.pm.org/mailman/listinfo/toronto-pm
>
>


More information about the toronto-pm mailing list