Pushing scalars into temporary arrays to extract data is not as uncommon as it may seem;the side effect of such practices is, that memory is being wasted. Iterating through an array (lets say for (my $i; $i < @array; $i++)) and choping out unneeded items with splice() is a subtle trap since $#array will constantly be shrinked; how can we determine reliably at which array index to throw out an item without endangering its surrounding items?
Following piece of code attempts to outline such an approach. The sub &filter_stuff takes as first argument an arrayref, and as second argument an array consisting of regular expressions. If a certain item within the arrayref ($stuff) doesn't match all expressions, it will be choped out.
sub filter_stuff { my $stuff = shift; my @patterns = @_; for (my $match, my $i = 0; $i < @$stuff; $i++ if $match) { for (@patterns) { $match = $$stuff[$i] =~ /$_/; splice(@$stuff, $i, 1) && last unless $match; } } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: extracting splices with a for-loop and splice()
by Roy Johnson (Monsignor) on Jan 28, 2004 at 18:12 UTC | |
by Anonymous Monk on Jan 28, 2004 at 19:32 UTC | |
|
Re: extracting splices with a for-loop and splice()
by rcaputo (Chaplain) on Jan 29, 2004 at 04:59 UTC | |
|
Re: extracting splices with a for-loop and splice()
by ysth (Canon) on Jan 28, 2004 at 17:01 UTC | |
by Anonymous Monk on Jan 28, 2004 at 17:11 UTC |