neversaint has asked for the wisdom of the Perl Monks concerning the following question:

Dear Masters,
How can I quickly/efficiently insert the numerical value in between alphabet from $inst into between strings of each element in $arref1.

Note that the numbers of alphabet in $inst1 are always exactly the same with numbers of string in each element of $arref1. Here is the example of it:
my $arref1 = [ 'foo bar quux bam', 'foi bir quix bim', 'foe ber quex bem', 'foa bor quax bom',]; my $inst1 = '4 A -4 C -4 B 2 D'; # intended result my @result1 = ( 'foo -4 bar -4 quux 2 bam', 'foi -4 bir -4 quix 2 bim', 'foe -4 bar -4 quex 2 bem', 'foa -4 bor -4 quax 2 bom', );
Other example:
my $arref2 = [ 'foo bam', 'foi bim', 'foe bem', 'foa bom', ]; my $inst2 = '3 A -2 D'; # intended result my @result2 = ( 'foo -2 bam', 'foi -2 bim', 'foe -2 bem', 'foa -2 bom', );
I really don't know how to go about it. Please kindly advice.


---
neversaint and everlastingly indebted.......

Replies are listed 'Best First'.
Re: Howto insert numbers into between strings alternately
by GrandFather (Saint) on Oct 22, 2005 at 08:26 UTC
    use warnings; use strict; my @array = ( 'foo bar quux bam', 'foi bir quix bim', 'foe ber quex bem', 'foa bor quax bom', ); my $inst1 = '4 A -4 C -4 B 2 D'; my @result1; my @inserts; $inst1 =~ /[\d+-]+(?: \w ([\d+-]+)(?{push @inserts, $1}))*/g; for my $line (@array) { my $index = 0; $line =~ s/\b /' '.$inserts[$index++].' '/eg; push @result1, $line; } print join "\n", @result1;

    Prints:

    foo -4 bar -4 quux 2 bam foi -4 bir -4 quix 2 bim foe -4 ber -4 quex 2 bem foa -4 bor -4 quax 2 bom

    Update: Oh, and using the alternate data set prints:

    foo -2 bam foi -2 bim foe -2 bem foa -2 bom

    Perl is Huffman encoded by design.
Re: Howto insert numbers into between strings alternately
by pg (Canon) on Oct 22, 2005 at 15:18 UTC

    Or:

    use Data::Dumper; use strict; use warnings; my $array = [ 'foo bar quux bam', 'foi bir quix bim', 'foe ber quex bem', 'foa bor quax bom' ]; my $ins = '4 A -4 C -4 B 2 D'; my @ins = split(/\s+/, $ins); my @result; for my $line (@$array) { my @pieces = split /\s+/, $line; my @joined; for my $j (0 .. $#pieces) { push @joined, $pieces[$j]; push @joined, $ins[$j* 2 + 2] unless ($j == $#pieces); } push @result, join(" ", @joined); } print Dumper(\@result);