It's not clear to me exactly what you're trying to do, but you've sinned against a big no-no:
Do not modify an array in a foreach loop over the same array.
What I do, if I don't mind the array being eaten in the process, is something like this:
$\ = "\n"; # append newline after print
@a = 'a';
while(@a) { # there's stuff left in the array
my $item = shift @a; # remove it, ready to process
print $item;
if(rand() < 0.8) {
# sometimes add a new item
push @a, ('a' .. 'z')[int rand 26];
}
}
Example output:
a
p
i
n
o
q
e
p
k
You see? while doesn't mind at all if the item to loop over, changes under it. foreach does.
That's one way that you can, for example, replace a recursive implementation of a file digger that does something like File::Find, with an iterative one: just push new directories you encounter while processing a directory, onto the to-do array.