http://www.perlmonks.org?node_id=443924

Say, you have "a,b,c,d,e" and want a "f" after "c":
```   @array = map { \$_ eq "c" ? ("c","f") : \$_ } @array
but this would insert "f" for each "c" you have.

Alberto Simões

Replies are listed 'Best First'.
Re^2: Inserting an element into an array after a certain element
by RazorbladeBidet (Friar) on Mar 31, 2005 at 18:58 UTC
You could easily fix that by adding a counter:
```@array = map { \$_ eq "c" && !\$found++ ? ("c","f") : \$_ } @array
(as a sub)
``` sub insert_after_first {
my \$arr_ref = shift;
my \$to_insert = shift;
my \$insert_after_me = shift;

my \$found = 0;

map { \$_ eq \$insert_after_me && !\$found++ ? ( \$insert_after_me, \$to
+_insert ) : \$_ } @\$arr_ref;
}
--------------
"But what of all those sweet words you spoke in private?"
"Oh that's just what we call pillow talk, baby, that's all."
Re^2: Inserting an element into an array after a certain element
by ikegami (Pope) on Mar 31, 2005 at 19:07 UTC

Ajusted to only do it once:

```my \$first = 1;
@array = map {
if (\$first && \$_ eq "c") {
\$first = 0;
(\$_, "x")
} else {
\$_
}
} @array;

hum, ugly. How about:

```my \$first = 1;
@array = map {
my @a = \$_;
push(@a, "x") if (\$first && \$_ eq "c");
\$first ||= @a-1;
@a
} @array
```foreach (0..\$#array) {