我有四个数组@A1
,@A2
,@A3
,@A4
,每个数组都有相同数量的元素,比如6。
我想创建一个存储两个数组元素值的二维数组
我想要输出对应于以下格式。
例如
Array1: A B C D E F
Array2: E F G H I J
Array3: Q W E R T Y
Array4: P O L I U G
然后矩阵应该是:
[0,0] = A E [0,1] = B F [0,2] = C G [0,3] = D H [0,4] = E I [0,5] = F J
[1,0] = Q P [1,1] = W O [1,2] = E L [1,3] = R I [1,4] = T U [1,5] = Y G
我将为大量数组执行上述操作而不仅仅是4.所以我将不得不编写某种循环。
有关做同样事情的任何建议吗?
答案 0 :(得分:2)
希望这有帮助。
use strict;
use warnings;
my @A1 = qw'A B C D E F';
my @A2 = qw'E F G H I J';
my @A3 = qw'Q W E R T Y';
my @A4 = qw'P O L I U G';
my @matrix;
$matrix[0][4] = [ $A1[3], $A2[3] ];
# Use one of the following
for(
my $i=0;
$i<@A1 || $i<@A2 || $i<@A3 || $i<@A4;
$i++
){
$matrix[0][$i+1] = [ $A1[$i], $A2[$i] ];
$matrix[1][$i+1] = [ $A3[$i], $A4[$i] ];
}
# OR
for(
my $i=0;
$i<@A1 || $i<@A2 || $i<@A3 || $i<@A4;
$i++
){
push @{ $matrix[0] }, [ $A1[$i], $A2[$i] ];
push @{ $matrix[1] }, [ $A3[$i], $A4[$i] ];
}
# OR
{
my $i = 1;
for my $elem (@A1){
push @{ $matrix[0][$i++] }, $elem;
}
$i = 1;
for my $elem (@A2){
push @{ $matrix[0][$i++] }, $elem;
}
$i = 1;
for my $elem (@A3){
push @{ $matrix[1][$i++] }, $elem;
}
$i = 1;
for my $elem (@A4){
push @{ $matrix[1][$i++] }, $elem;
}
}
# notice how $i is out of scope here
要打印出来,您可以使用Data::Dumper或YAML
use 5.010;
use Data::Dumper;
$Data::Dumper::Terse = 1;
$Data::Dumper::Indent = 1;
say Dumper \@matrix;
use YAML;
say Dump \@matrix;
use Data::Dump 'dump';
say dump \@matrix;
<强> Data::Dumper 强>
[ [ [ 'A', 'E' ], [ 'B', 'F' ], [ 'C', 'G' ], [ 'D', 'H' ], [ 'E', 'I' ], [ 'F', 'J' ] ], [ [ 'Q', 'P' ], [ 'W', 'O' ], [ 'E', 'L' ], [ 'R', 'I' ], [ 'T', 'U' ], [ 'Y', 'G' ] ] ]
<强> YAML 强>
--- - - - A - E - - B - F - - C - G - - D - H - - E - I - - F - J - - - Q - P - - W - O - - E - L - - R - I - - T - U - - Y - G
<强> Data::Dump 强>
[ [ ["A", "E"], ["B", "F"], ["C", "G"], ["D", "H"], ["E", "I"], ["F", "J"], ], [ ["Q", "P"], ["W", "O"], ["E", "L"], ["R", "I"], ["T", "U"], ["Y", "G"], ], ]
答案 1 :(得分:0)
我的猜测产生了以下程序:
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my @a1 = ( 10 .. 19 );
my @a2 = ( 20 .. 29 );
my @matrix;
for ( my $i = 0 ; $i < @a1 ; $i++ ) {
push @matrix, [ $a1[$i], $a2[$i] ];
}
print Dumper \@matrix;