[Chicago-talk] Removing an element from an array

Brian Katzung briank at kappacs.com
Fri Jul 11 10:58:34 PDT 2008

Hi Mike.

Per "man perlsyn":

     If any part of LIST is an array, "foreach" will get very confused if
     you add or remove elements within the loop body, for example with
     "splice". So don't do that.

I recommend building a new list. You can either retain or consume the 
old list.

# Retain original array
my @subset;
foreach $symbol (@symbol)
	push(@subset, $symbol) if (conditions);

# Consume original array
my @subset;
while (defined($symbol = shift(@symbol))
	push(@subset, $symbol) if (conditions);

   - Brian

Mike Demir wrote:
> Hi:
> So here is my quandry. I have a list of stock symbols stored in array 
> (@sym), and am looking to test each symbol against a series of 
> conditions  (foo1, foo2....). When the condition is met, I would like to 
> remove that symbol and return to the top of the loop to start working on 
> the next symbol. I'm having no trouble getting the test conditions to 
> work, or the looping to work. However I can't seem to remove the symbol 
> from the array. It's a conceptual thing at this point, so a solution is 
> nice but not required. Need to understand.
> So here's what I had attempted...
> foreach $symbol(@symbol) {
>             if(foo1)

Brian Katzung, Kappa Computer Solutions, LLC
Leveraging UNIX, GNU/Linux, open source, and custom
software solutions for business and beyond
Phone: 877.367.8837 x1  http://www.kappacs.com

More information about the Chicago-talk mailing list