在 Perl 中构建和打印多维列表而无需循环 [英] Building and printing a multidimensional list in Perl without looping

查看:87
本文介绍了在 Perl 中构建和打印多维列表而无需循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章的最佳答案:如何创建多维Perl 中的数组? 建议按如下方式构建多维数组:

我的@array = ();foreach 我的 $i ( 0 .. 10 ) {foreach 我的 $j ( 0 .. 10 ) {推@{ $array[$i] }, $j;}}

我想知道是否有一种方法可以更紧凑地构建数组并避免嵌套循环,例如使用类似的东西:

我的@array = ();我的@other_array = (0 ... 10);foreach 我的 $i ( 0 .. 10 ) {$array[$i] = @other_array;# 这在 Perl 中不起作用}}

Perl 是否支持用于构建多维数组而无需嵌套循环的任何语法?

同样,有没有办法在没有(嵌套)循环的情况下打印多维数组?

解决方案

有不止一种方法可以做到:

生成

push 接受 LISTs

我的@array;push @{$array[$_]}, 0 .. 10 for 0 .. 10;

替代语法:

我的@array;push @array, [ 0 .. 10 ] for 0 .. 10;

map 养眼强>

my @array = map { [ 0 .. 10 ] } 0 .. 10;

替代语法:

my @array = map [ 0 .. 10 ], 0 .. 10;

打印

最小循环

为@array打印@$_\n";

在 Perl 5.10+ 上

使用特性'say';为@array 说@$_";

更多的格式控制

print join( ', ', @$_ ), "\n" for @array;# "0, 1, 2, ... 9, 10"

无循环"(循环对你隐藏)

use Data::Dump 'dd';dd @array;

Data::Dumper

使用Data::Dumper;打印转储器 \@array;

<小时>

查看perldoc perllol 了解更多详情>

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

push accepts LISTs

my @array;
push @{$array[$_]}, 0 .. 10 for 0 .. 10;

Alternative syntax:

my @array;
push @array, [ 0 .. 10 ] for 0 .. 10;

map eye-candy

my @array = map { [ 0 .. 10 ] } 0 .. 10;

Alternative syntax:

my @array = map [ 0 .. 10 ], 0 .. 10;

Printing

With minimal looping

print "@$_\n" for @array;

On Perl 5.10+

use feature 'say';
say "@$_" for @array;

With more formatting control

print join( ', ', @$_ ), "\n" for @array;   # "0, 1, 2, ... 9, 10"

"No loops" (The loop is hidden from you)

use Data::Dump 'dd';
dd @array;

Data::Dumper

use Data::Dumper;
print Dumper \@array;


Have a look at perldoc perllol for more details

这篇关于在 Perl 中构建和打印多维列表而无需循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆