The question then is is this violation of the general prohibition safe or was I lucky
Now I am confused. What do you expect,
- Perl loops over the original array, whatever you do to the array in the meantime
- Perl loops over the modified array
Frankly, I have no idea what to expect, you can make a case for both behaviors. In such a case, I'd say: don't do it. What will happen in this case
might change over time, possibly because someone decided to fix perl's "erratic behavior".
What I think is safe, is this:
- Loop over the original array: make a temporary copy.
foreach(my @temp = @arr) {
push @arr, 'd' if $_ eq 'a';
push @arr, 'e' if $_ eq 'b';
push @arr, 'f' if $_ eq 'c';
print $_;
}
- if you want to loop over the modified array, use the loop index:
for(my $i = 0; $i < @arr; $i++) {
local $_ = $arr[$i];
push @arr, 'd' if $_ eq 'a';
push @arr, 'e' if $_ eq 'b';
push @arr, 'f' if $_ eq 'c';
print $_;
}
p.s. I was expecting this to work:
foreach(() = @arr) {
print;
}
but it doesn't loop even once. I think that's a bit weird, since
$x = () = @arr;
actually sets $x to the size of the array.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.