http://qs1969.pair.com?node_id=1023518


in reply to Is it safe to append to the array you are iterating over

G'day DrWhy,

In what sense does that code work? In what sense do you consider it to be safe?

I don't see any code requesting for warnings to be emitted. I don't see any sanity checks. I don't see any tests for ... well, anything. Perhaps worked safely means it finished before flames burst forth from the back of your computer :-)

What would happen if, at some later time, a fourth conditional push() was added:

push @arr, $some_var if $_ eq 'd';

If $some_var happens to evaluate to 'a', you're now stuck in an infinite loop.

There's all sorts of other scenarios that result in infinite loops, chewing up inordinate amounts of processor or memory resources, leaving the array in a state that has adverse consequences for subsequent processing and so on.

In general, this practice is not safe; moreover, it can easily be avoided.

-- Ken