The top answer in this post: How can I create a multidimensional array in Perl? suggests building a multi-dimensional array as follows:
my @array = ();
foreach my $i ( 0 .. 10 ) {
foreach my $j ( 0 .. 10 ) {
push @{ $array[$i] }, $j;
}
}
I am wondering if there is a way of building the array more compactly and avoiding the nested loop, e.g. using something like:
my @array = ();
my @other_array = (0 ... 10);
foreach my $i ( 0 .. 10 ) {
$array[$i] = @other_array; # This does not work in Perl
}
}
Does Perl support any syntax like that for building multi-dimensional arrays without nested looping?
Similarly, is there a way to print the multidimensional array without (nested) looping?
There is more than one way to do it:
Generating
pushacceptsLISTsAlternative syntax:
mapeye-candyAlternative syntax:
Printing
With minimal looping
On Perl 5.10+
With more formatting control
“No loops” (The loop is hidden from you)
Data::DumperHave a look at
perldoc perllolfor more details