Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
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..."

In reply to Is it safe to append to the array you are iterating over by DrWhy

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, 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, 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.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others surveying the Monastery: (2)
    As of 2018-04-27 05:03 GMT
    Find Nodes?
      Voting Booth?