[Chicago-talk] Delete element from array

Andy_Bach at wiwb.uscourts.gov Andy_Bach at wiwb.uscourts.gov
Fri Jul 11 11:14:58 PDT 2008


As you found:

           if (foo1) {
            delete $symbol[];
            next;

doesn't work - You've got nothing in the array box, so you probably end up
deleting element zero.  Basically you're running into the array iterator
question, C-ishly you could do (note, I pluralized the array name):
for (my $i = 0; $i < $#symbols, $i++) {
  if ( foo ) {
     delete $symbols[$i];

Other options are keeping track of symbols you want removed and removing
all at the end or using grep
   if ( foo ) {
     # delete
     $badsymbols .= ($badsymbols ? '|' : '' ) . 'foo';
...
}   # foreach
@symbols = grep { ! /$badsymbols/ } @symbols;

afterwards. Here you need to worry about anchors if there is overlap (e.g.
"foo" and "fool" are possible).  You can take advantage of the fact that in
the for loop the scalar that gets the array element is a ref to the actual
array element.  That is, if you undefined the scalar, it undefines the
element in the array so:
use warnings;
use strict;
my @symbols = qw(foo fiv fib fink fort futz);
print "Sym: ", join(", ", @symbols), "\n";
foreach my $symbol (@symbols) {

            if ($symbol eq 'fib') {
              #delete $symbol[];
              undef($symbol);
              next;
            };

}
@symbols = grep { defined() } @symbols;
print "Sym: ", join(", ", @symbols), "\n";


a
-------------------
Andy Bach
Systems Mangler
Internet: andy_bach at wiwb.uscourts.gov
Voice: (608) 261-5738 Fax: 264-5932

Accordion, n.:        A bagpipe with pleats.



More information about the Chicago-talk mailing list