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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|