交替循环嵌套的foreach循环 [英] Alternate looping nested foreach loops
问题描述
我正在尝试从一个foreach循环中打印一个值.然后转到另一个foreach循环,继续直到两个数组中的最后一个元素.
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;
}
}
这将从第二个foreach循环返回相同的值.
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
所需的输出应如下:
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?
我正在测试此逻辑,因为我将在我的脚本中使用它.在哪里,我将从foreach循环中打开一对文件并对其进行处理(每个循环一个文件).我将使用foreach循环打开的文件在单独的目录中,并且在几个类似文件的池中.我将循环使用嵌套的foreach逻辑打开所有代码.
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.
脚本看起来像这样:
$dir1 = "/tmp/*";
$dir2 = "/home/*";
@files1 = glob( $dir1 );
@files2 = glob( $dir2 );
foreach (@files1) {
.
.
.
foreach (@files2){
.
.
.
}
}
推荐答案
您正在从
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";
}
输出:
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
这篇关于交替循环嵌套的foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!