[Chicago-talk] Removing an element from an array

Steven Lembark lembark at wrkhors.com
Fri Jul 11 15:33:54 PDT 2008


> 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)
> 

With every you can remove the current item without
confusing Perl but you have to finish the cycle
each time.

If you want to remove arbitrary data, that sounds
more like a hash: iterating the keys won't get
confused if you delete a value since the list of
keys is taken as a snapshot when the loop starts.

       my %sym2data      = ();

       # build whatever data structure you want.
       # instead of pusing the values onto one
       # long queue insert them as data keyed
       # by the symbol -- or whatever unit of
       # processin you like.

       push @{ $sym2data{ $symbol } }, [ blah blah blah ];

       ...

       for my $sym ( keys %sym2data )
       {
             if( $sym ~~ whatever )
             {
                   my $data    = delete $sym2data{ $sym };

                   for( @$data )
                   {
                         # do what you want with the data
                   }

                   # now the data goes out of scope and
                   # you recover the space.
             }
       }

If you need the keys in order use something like:

       for my $sym ( sort keys %sym2data )
       {
             ...
       }

If you need to keep cycling through incoming data
you can put a data acquisition point at the start
of each loop:

       LOOP:
       for( ;; )
       {
             add_more_data \%sym2data;

             for my $sym ( keys %sym2data )
             {
                   if( $sym ~~ whatever )
                   {
                         # do the deed

                         next LOOP
                   }
             }
       }

again, the point is that you can delete $hash{ $key }
while iterating keys %hash with impunity.


More information about the Chicago-talk mailing list