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