in reply to Re: How do I completely remove an element from an array?
in thread How do I completely remove an element from an array?
There is still the issue of fun things that happen when you edit an array that is used in the controlling loop (as others also pointed out above), so the grep solution gets fun with something like the following not working as one might think:
foreach my $item ( (@array1, @array2) ) { if ( $item =~ /$pattern/i ) { @array1 = grep { $_ != $item } @array1; } }
A solution I'll use to avoid all of the hard thinking is to just create a list of items to remove in the loop, and then as a separate operation delete them all:
my @toRemove; foreach my $item ( (@array1, @array2) ) { if ( $item =~ /$pattern/i ) { push(@toRemove, $item); } } foreach my $item ( @toRemove ) { @array1 = grep { $_ ne $item } @array1; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Answer: How do I completely remove an element from an array?
by doug (Pilgrim) on Apr 23, 2009 at 17:25 UTC | |
Re^2: Answer: How do I completely remove an element from an array?
by gone2015 (Deacon) on Apr 23, 2009 at 10:33 UTC |
In Section
Seekers of Perl Wisdom