First off, while not exactly perfectly worded for this question (is push different from splice?), the foreach documentation in perlsyn says, in part:

If any part of LIST is an array, "foreach" will get very confus +ed if you add or remove elements within the loop body, for example wi +th "splice". So don’t do that.
I think that says "no".

Now, as to how to do this: no, I don't know a clean way to do that, either. map doesn't quite do it:

@foo = map { 'd' eq $_ ? ($_,'h') : $_ } @foo; # puts 'h' right after 'd'
And using an extra variable doesn't quite help, either:
my @extras; foreach my $x (@foo) { push @extras, 'h' if $x eq 'd'; print $x; } push @foo, @extras; # didn't print 'h'. But if we add: print foreach @extras; # that works ... but duplicates code.
Looks like the guaranteed solution is a bit longer:
{ my @extras; foreach my $x (@foo) { push @extras, 'h' if $x eq 'd'; } push @foo, @extras; } foreach my $x (@foo) { print $x; }
Even that misses it in some cases - for example, if what you're pushing onto @foo may need to be treated itself. In this case, imagine pushing on a random letter which itself may be 'd' - and thus you want to push on an extra random letter each time you get another 'd'. Theoretically this may not ever end, but practically you'll stop getting 'd's eventually.


In reply to Re: changing array size in foreach loop: is it safe? by Tanktalus
in thread changing array size in foreach loop: is it safe? by Errto

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.