in reply to self-feeding infinite loop
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:
Example output:$\ = "\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]; } }
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: self-feeding infinite loop
by Dominus (Parson) on Aug 20, 2007 at 14:02 UTC | |
by eric256 (Parson) on Aug 20, 2007 at 16:33 UTC | |
by Dominus (Parson) on Aug 20, 2007 at 16:50 UTC | |
by eric256 (Parson) on Aug 20, 2007 at 18:55 UTC | |
by Dominus (Parson) on Aug 20, 2007 at 20:01 UTC | |
| |
|
Re^2: self-feeding infinite loop
by spx2 (Deacon) on Aug 18, 2007 at 14:03 UTC | |
by bart (Canon) on Aug 18, 2007 at 14:17 UTC | |
by syphilis (Archbishop) on Aug 18, 2007 at 14:33 UTC | |
by Errto (Vicar) on Aug 18, 2007 at 18:03 UTC |