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

VVP:arrays of the same size.

by vivekvp (Acolyte)
on Mar 20, 2002 at 20:22 UTC ( #153115=perlquestion: print w/ replies, xml ) Need Help??
vivekvp has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I have to arrays read in from a file called @a and @b. Both have the save number of elements... Can I use them in one FOREACH loop or do I need 2? i.e.
foreach $a(@a) { print "a- $a b - $b \n" }
Or do I have to...
$cnt=@a; for ($count=0;$count<$cnt;$count++) { print "a $a[$count] b $b[$count] \n"; }
Any way to do that with a foreach? Thanks, V He who laughs last, doesn't get the joke.

Comment on VVP:arrays of the same size.
Select or Download Code
Re: VVP:arrays of the same size.
by dragonchild (Archbishop) on Mar 20, 2002 at 20:40 UTC
    There's a few ways to do it. The most intuitive is the following:
    for (my $i = 0; $i < @a; $i++) { # Do stuff with @a and @b }
    Another way would be to make a temporary hash and use each. This means you don't care what order stuff is done in, so long as the Nth element of @a is processed with the Nth element of @b.
    my %temp; @temp{@a} = @b; while (my ($a_val, $b_val) = each %temp) { # Do stuff with $a_val and $b_val }
    The first is clearer and easier to work with. Plus, it allows the addition of some @c later on in the future.

    Now, if these are parallel arrays, you might want to consider doing the following:

    use mapcar; # This is on a node [tye] posted somewhere on PM my @temp_arr = mapcar { \@_ } (\@a, \@b); foreach my $vals (@temp_arr) { # Do stuff with $vals->[0] (from @a) and $vals->[1] (from @b) }
    That makes it very clear they are parallel arrays. *shrugs* YMMV

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: VVP:arrays of the same size.
by dreadpiratepeter (Priest) on Mar 20, 2002 at 20:41 UTC
    look at mapcar. It allows you to iterate through multiple arrays simultaneously.

    -pete
    "I am Jack's utter lack of disbelief"
      You probably mean this mapcar.

      /prakash

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://153115]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2014-08-01 00:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (255 votes), past polls