问题
I am trying to print a value from one foreach loop. Then go to the other foreach loop and continue until the last elements in both arrays.
@list = (10, 20, 30, 40, 50);
@list1 = (15, 25, 35, 45, 55);
OUTER:foreach $a (@list) {
print "value of a: $a\n";
foreach $b (@list1) {
print "value of b: $b\n";
next OUTER;
}
}
This returns the same value from the second foreach loop.
value of a: 10
value of b: 15
value of a: 20
value of b: 15
value of a: 30
value of b: 15
value of a: 40
value of b: 15
value of a: 50
value of b: 15
The desired output should be as follows:
value of a: 10
value of b: 15
value of a: 20
value of b: 25
value of a: 30
value of b: 35
value of a: 40
value of b: 45
value of a: 50
value of b: 55
Is there a way I can print values from both arrays alternately?? Any loop control statements can do this?
I am just testing this logic because I am going to use it in a script of mine. Where, I will be opening a pair of files from the foreach loops and process it (one file per loop). The files I will be opening using foreach loops are in separate directories and are in a pool of several similar files. I will be looping in my code to open all of them using the nested foreach logic.
The script would look something like this:
$dir1 = "/tmp/*";
$dir2 = "/home/*";
@files1 = glob( $dir1 );
@files2 = glob( $dir2 );
foreach (@files1) {
.
.
.
foreach (@files2){
.
.
.
}
}
回答1:
You are describing the behavior of each_array
from List::MoreUtils:
use strict;
use warnings;
use 5.010;
use List::MoreUtils qw(each_array);
my @arr1 = (10, 20, 30, 40, 50);
my @arr2 = (15, 25, 35, 45, 55);
my $it = each_array(@arr1, @arr2);
while (my ($a1, $a2) = $it->()) {
say "value from array 1: $a1";
say "value from array 2: $a2";
}
Output:
value from array 1: 10
value from array 2: 15
value from array 1: 20
value from array 2: 25
value from array 1: 30
value from array 2: 35
value from array 1: 40
value from array 2: 45
value from array 1: 50
value from array 2: 55
回答2:
Loop over the index of either of the arrays
foreach my $i (0..$#list) {
say "value of a: ", $list[$i] // 'undef'; #/
say "value of b: ", $list1[$i] // 'undef';
}
where
defined-or
(//
)
is needed or you'll get warnings for undefined elements (or if the second array gets exhausted before the first one). I print the string undef
, adjust as suitable.
This clearly assumes that it makes sense processing the arrays in parallel and so that they are of equal size. If they are not you may want to do something other than carry on once one ends.
Your code exits the inner loop after the first iteration with next
, and the next time it returns to it it starts from the beginning.
来源:https://stackoverflow.com/questions/50729354/alternate-looping-nested-foreach-loops