CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Array element deletion/splice problem

 



circle
New User

Aug 31, 2008, 9:50 AM

Post #1 of 2 (614 views)
Array element deletion/splice problem Can't Post

Hi all!

I have this problem that I'm kinda stuck with. I found out after a while that deleting elements in an array while iterating through it was a bad idea...naturally! Doh! I'm kinda fresh on dealing with arrays in this manner.

Anyway, I was trying to take on the problem by doing the following, which how ever did not work either, resulting in, saying the least, even more strange results. It is like it is inverted. The routine removes the elements that should be saved and saves those that are supposed to be deleted.

Anyway, here's the code, which is part of a subroutine:

Code
foreach my $Row (@AllRows){ 
if ($Row =~ m/MatchSomeThing/) {
push @WantedRows, $Row;
#splice(@AllRows, $RowCount, 1); (Obviously doesn't work!)
splice(@AllRows, $RowCount, 1, "--Row Processed--\n");
push @RowsToDelete, $RowCount;
}
$RowCount++;
}

foreach my $DeleteRow (@RowsToDelete) {
splice(@AllRows, $DeleteRow, 1);
}


At the moment, I'm all blind. Been staring at this for too long. Any advice or hints appreciated. I'm pretty sure it all can be optimized as well.

Thanks for your time!
Regards
/Thomas


KevinR
Veteran


Aug 31, 2008, 12:02 PM

Post #2 of 2 (613 views)
Re: [circle] Array element deletion/splice problem [In reply to] Can't Post

Don't bother with the splicing, push the rows you want to keep into a new array, then assign the valu eof the new array to the old array.:




Code
   

for $stuff (@foo) {

push @keep,$stuff if (/foo/);

}

@foo = @keep

-------------------------------------------------

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives