no1
no1

Reputation: 727

How do I pass multiple arrays to a 'foreach' loop in Perl?

I want to write items from two arrays into a file, like

 @a = ('1', '2', '3')
 @b = ('0.1', '0.2', '0.3')

I want my output like this:

1 0.1
2 0.2
3 0.3

in the file.

I tried using two foreach loops, which is obviously wrong,

 foreach my $a (@a) {
    foreach my $b (@b) {
        print FP "$a $b \n";
    }
 }

This is wrong. How do I pass multiple arrays to a foreach loop in Perl?

Upvotes: 2

Views: 5696

Answers (2)

mpapec
mpapec

Reputation: 50677

If you want to output all elements of @a and @b in parallel, you can loop through all indices of one of them (arrays are of same size so it doesn't matter which), and use it to access actual elements ($a[$i] and $b[$i])

foreach my $i (0 .. $#a) {
  print "$a[$i] $b[$i] \n";
}

Upvotes: 8

Chris
Chris

Reputation: 729

@a=('1','2','3');
@b=('0.1','0.2','0.3');

print "$a[$_] $b[$_] \n" for (0 .. $#a);

Of course this assumes @a and @b are of equal lengths.

Upvotes: 7

Related Questions