Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (5)
As of 2024-04-25 23:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found