In your code you have a nested foreach structure. You will loop through num of elements in first array times the number of elements in the second array. This means you will be printing more than the output you want. For example you will call print 25 times instead of 5 times. Surely you can work with the structure you have by putting flags or using internal indices but it just gets messy and the problem you are trying to solve clearly does not require a nested loop. If you really like the foreach structure you can create an AoA (shown in my code below).

You said you are new so let me explain some things that are not immediately obvious -

$/ - think of this as your new line character (line separator character). see perlvar for more details.

[value1,value2] - creates a reference to the list  (value1,value2). Note square brackets

$_ - for/foreach loops populate this variable when we don't specify the looping variable explicitly.

update: missed this one-- @$_[0] and @$_[1] - In the AoA case each element is a "reference" to a list. So you have treat them as arrays when you want individual elements of each ref. $_ in the AoA contains a list now. The @ before $_ helps in dereferencing the list for us.

#!/usr/bin/perl -w use strict; my @num = qw (1 2 3 4 5); my @alp = qw (A B C D E); for (0..$#num) { print $num[$_], "-", $alp[$_],$/; } ### OR CREATE AOA my @AoA = (); for (0..$#num) { push @AoA, [$num[$_], $alp[$_]]; } print $/; foreach (@AoA) { print @$_[0], "-", @$_[1],$/; } __END__ 1-A 2-B 3-C 4-D 5-E 1-A 2-B 3-C 4-D 5-E

In reply to Re: Concordance Printing of Two Arrays by sk
in thread Concordance Printing of Two Arrays by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.