Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

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
Replies are listed 'Best First'.
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.

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


Log In?

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

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2016-05-31 17:23 GMT
Find Nodes?
    Voting Booth?