On Fri, May 14, 2004 at 10:35:45PM -0500, Andrew Gaffney wrote: > Charles K. Clarkson wrote: > >Andrew Gaffney <[EMAIL PROTECTED]> wrote: > >: > >: This doesn't quite work because I'm removing elements > >: from the array I'm looping through. What would be the > >: best way to take care of this? > > > > Don't use splice: :) > > > >print Dumper $array1; > > > >@$array1 = grep ! /^!/, @$array1; > > > >print Dumper $array1;
Note that using grep constructs a whole new array and is potentially very slow if working with large arrays--especially if the array is tied to (e.g.) a database. Which is not to say you _shouldn't_ use grep...just make sure you know something about the size of your data. I use a 'for' loop below, which will have the same problem. > Well, I'm working with the data in the array at the same time I'm trying to > remove certain elements. I need to process the elements that start with a > '!' and then remove them. I process all other elements differently. This should do what you want. It also does it in one pass, and without counting backward or any other fancy tricks. #!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $a = [qw(foo bar baz !jaz frob quux)]; print Dumper $a; my $i = 0; for (@$a) { unless ( /^!/ ) { process_normal_item($_); $i++; } else { process_negated_item($_); splice @$a, $i, 1; $_ = $a->[$i]; redo; } } print Dumper $a; # These are only here to provide you with convenient hooks for # expanding this into your own code. # sub process_normal_item { print shift; } sub process_negated_item { print shift; } -- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>