Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: Concordance Printing of Two Arrays

by sk (Curate)
on Oct 17, 2005 at 03:20 UTC ( #500647=note: print w/replies, xml ) Need Help??

in reply to Concordance Printing of Two Arrays

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://500647]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2017-09-23 06:02 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (271 votes). Check out past polls.