First off, while not exactly perfectly worded for this question (is push different from splice?), the foreach documentation in perlsyn says, in part:
I think that says "no".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.
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:
And using an extra variable doesn't quite help, either:@foo = map { 'd' eq $_ ? ($_,'h') : $_ } @foo; # puts 'h' right after 'd'
Looks like the guaranteed solution is a bit longer: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.
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.{ my @extras; foreach my $x (@foo) { push @extras, 'h' if $x eq 'd'; } push @foo, @extras; } foreach my $x (@foo) { print $x; }
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |