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

I have been working hard to find the solution on my own however I have not comprehended the iteration and concatenation. I would appreciate a hint or someone to point me in the right direction
my @numbers = (4,7,11,14); my @numbers2= @numbers; my @numbers3= map {"$numbers[$_]$numbers2[$_]"} 1..$#numbers ; # result 447711111414 my $white ='w '; my $rye =' r '; my $italian = 'i '; my $french = ' f '; WANT THIS $final_string = 'w 4 r i 4 f i 7 r w 7 f w 11 r i 11 f i 14 r w 14 f';
The @numbers array element count will vary.
There are four sandwich patterns repeated .
1st element is preceded with $white followed by $rye (5th,9th,etc)
2nd element is preceded with $italian followed by $french (6th,10th,etc)
3rd element is preceded with $italian followed by $rye (7th,11th,etc)
4th element is preceded with $white followed by $french (8th,12th,etc)
after iterating it would be $final_string

Replies are listed 'Best First'.
Re: array and concatenate
by GrandFather (Saint) on Jul 09, 2011 at 07:51 UTC

    If I understand what you want the following should do the trick:

    use strict; use warnings; my @numbers = map {$_, $_} (4, 7, 11, 14); my @breads = split '', 'wrifirwf'; my @parts; my $breadIndex = $#breads; while (@numbers) { push @parts, $breads[$breadIndex = ($breadIndex + 1) % @breads]; push @parts,shift @numbers; push @parts,$breads[$breadIndex = ($breadIndex + 1) % @breads]; } print join ' ', @parts;

    Prints:

    w 4 r i 4 f i 7 r w 7 f w 11 r i 11 f i 14 r w 14 f

    The key is to recycle the breads using the modulus operator to wrap the bread index.

    True laziness is hard work
Re: array and concatenate
by johngg (Canon) on Jul 09, 2011 at 12:00 UTC

    Here is a slight variation on GrandFather's solution that shows you how you could construct your array of @numbers by using a list repetition operator (see "x" in Multiplicative Operators) inside the map. It also shows you how to use an iterator to cycle round the list of breads. The iterator is a reference to a subroutine that returns the next element in the @breads array each time it is called ($breadsIter->()), resetting the element to zero whenever is has passed the end of the array.

    use strict; use warnings; use 5.010; my $breadsIter = do { my $idx = 0; my @breads = qw{ w r i f i r w f }; sub { $idx = 0 if $idx > $#breads; return $breads[ $idx ++ ]; }; }; my @numbers = map { ( $_ ) x 3 } 4, 7, 11, 14; my $finalStr = join q{ }, map { $breadsIter->(), $_, $breadsIter->() } @numbers; say $finalStr;

    The output.

    w 4 r i 4 f i 4 r w 7 f w 7 r i 7 f i 11 r w 11 f w 11 r i 14 f i 14 r + w 14 f

    I hope this is of interest.

    Cheers,

    JohnGG