Perl嵌套循环以不同的模式打印出两个数组n次

时间:2014-09-23 00:36:42

标签: arrays perl loops

我希望创建一个循环,其中多次打印以下数据。所以:"

n = 9;
@a = (1, 2 ,3);
@b = (a, b, c);


$a[0] = 1 $b[0] = a
$a[0] = 1 $b[1] = b
$a[1] = 2 $b[2] = c
$a[1] = 2 $b[0] = a
$a[2] = 3 $b[1] = b
$a[2] = 3 $b[2] = c
$a[0] = 1 $b[0] = a
$a[0] = 1 $b[1] = b
$a[1] = 2 $b[2] = c

1 个答案:

答案 0 :(得分:1)

看起来你只是在索引中骑行。

但是,您需要付出更多努力来澄清您的问题并展示您迄今为止所尝试的内容。

以下内容确实可以重现您想要的输出,但如果没有更多信息,它是否真的无法说明您实际需要的内容:

use strict;
use warnings;

my $n = 9;
my @a = qw(1 2 3);
my @b = qw(a b c);

for my $i ( 0 .. $n - 1 ) {
    my $a_index = ( $i / 2 ) % 3;
    my $b_index = $i % 3;
    printf "\$a[%d] = %s \$b[%d] = %s\n", $a_index, $a[$a_index], $b_index, $b[$b_index];
}

输出:

$a[0] = 1 $b[0] = a
$a[0] = 1 $b[1] = b
$a[1] = 2 $b[2] = c
$a[1] = 2 $b[0] = a
$a[2] = 3 $b[1] = b
$a[2] = 3 $b[2] = c
$a[0] = 1 $b[0] = a
$a[0] = 1 $b[1] = b
$a[1] = 2 $b[2] = c