perlquestion
DrWhy
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.
<p>
In Perl, is it safe to push new elements onto an array that you are currently looping over. E.g.:
<code>
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";
</code>
I have tested this and it does work. But I wonder if this practice is safe in general for Perl arrays?
<p>
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 (<tt>push</tt>), 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)?
<p>
The Perl I used to verify this is 'v5.10.0 built for x86_64-linux-thread-multi'
<p>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-144739">
<p><em>--DrWhy</em><p>
<em>"If God had meant for us to think for ourselves he would have given us brains. Oh, wait..."</em>
</div></div>