2014-09-23 49 views
-2

我正在創建一個循環,其中打印了以下數據n次。因此,考慮:」Perl嵌套循環以不同模式打印出兩個數組n次

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

看起來你只是通過索引循環

但是,你需要把更多的精力到這兩個澄清你的問題,表明你已經嘗試過這樣什麼。遠

下不會重現您想要的輸出,但它確實很難說,如果這是你真正需要的沒有更多的信息:

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]; 
} 

OUTP uts:

$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