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.
-
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.