If you don't mind destroying the two input arrays then an easy way is:
use warnings; use strict; my @a = qw(0 1 5 7 9 5 3); my @b = qw(a b c y e f z a a); my @new; while (@a && @b) { my $nextB = shift @b; if ($nextB =~ /[yz]/) { push @new, 'I'; } else { push @new, shift @a; } } print "@new";
Prints:
0 1 5 I 7 9 I 5 3
If you don't like destroying the input arrays, make a copy first. If they are very large and copying them is not an option come back for a slightly uglier solution.
Update: actually it's not really uglier:
use warnings; use strict; my @a = qw(0 1 5 7 9 5 3); my @b = qw(a b c y e f z a a); my @new; my $scanA = 0; for my $nextB (@b) { if ($nextB =~ /[yz]/) { push @new, 'I'; } else { last if $scanA >= @a; push @new, $a[$scanA++]; } } print "@new";
Output is the same as above (of course).
In reply to Re: add elements to array at certain positions
by GrandFather
in thread add elements to array at certain positions
by coldy
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |