DrWhy has asked for the wisdom of the Perl Monks concerning the following question:

My Google-fu is failing me today. This seems like a question that should have been answered already somewhere, but I can't find it.

In Perl, is it safe to push new elements onto an array that you are currently looping over. E.g.:

my @arr = qw/a b c/; foreach (@arr) { push @arr, 'd' if $_ eq 'a'; push @arr, 'e' if $_ eq 'b'; push @arr, 'f' if $_ eq 'c'; print $_; } print "\n";
I have tested this and it does work. But I wonder if this practice is safe in general for Perl arrays?

Point of clarification: I am asking about a specific use case that I have found that contradicts what the standard perl docs say about modifying arrays used in loop lists. If 1. the entire loop list is a single array and 2. the only modifications you make to this list inside the loop are appends (push), then the loop iterator recognizes the additional elements without getting 'confused'. The question then is is this violation of the general prohibition safe or was I lucky (e.g., is this behavior an implementation quirk specific to a version of Perl that could change without warning in different perl versions)?

The Perl I used to verify this is 'v5.10.0 built for x86_64-linux-thread-multi'


"If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."