Andy Greenwood wrote:
I have a reference to an annonymous array, which I am looping through with
foreach(@$servref) {
if ( checkServer($_, $dn) ) {
push(@$goodservref, $_);
} else {
# server wasn't good. Add another item to the list
push(@$servref, newitem);
}
}
Based on certain criteria, I want to add a new item to the end of the
$servref array. Is it safe to do this inside the foreach loop? If not,
what would be a better solution?
No it isn't safe - it is specifically warned against in perlsyn:
foreach (LIST) BLOCK
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.
Use this instead:
for (my $i = 0; $i < @$servref; $i++) {
my $serv = $servref->[$i];
if (checkServer($serv, $dn) ) {
push(@$goodservref, $serv);
}
else {
push(@$servref, $newitem);
}
}
HTH,
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>