[英]How can I initialize a 2D array in Perl?
How do I initialize a 2D array in Perl? 如何在Perl中初始化2D数组?
I am trying the following code: 我正在尝试以下代码:
0 use strict;
10 my @frame_events = (((1) x 10), ((1) x 10));
20 print "$frame_events[1][1]\n";
but it gives the following error: 但它给出以下错误:
Can't use string ("1") as an ARRAY ref while "strict refs" in use at ./dyn_pf.pl line 20.
在./dyn_pf.pl第20行使用“strict refs”时,不能使用字符串(“1”)作为ARRAY引用。
This syntax only seems to initialize a 1D array as print "$frame_events[1]\\n" works. 这种语法似乎只是初始化一维数组,因为打印“$ frame_events [1] \\ n”有效。 Though Perl doesn't give any error during the assignment.
虽然Perl在分配期间没有给出任何错误。
You cannot have an array of arrays in Perl, only an array of references to arrays. 你不能在Perl中有一个数组数组,只有一个数组引用数组。
my @frame_events = ([(1) x 10], [(1) x 10]);
print "$frame_events[1]->[1]\n";
Special case: you are free to omit the pointer dereferencing arrow between adjacent brackets (whether square or curly): 特殊情况:您可以省略相邻括号之间的指针解引用箭头(无论是方形还是卷曲):
print "$frame_events[1][1]\n";
In general you cannot have: 一般来说,你不能有:
You can have: 你可以 :
You can also have: 你也可以:
In Perl an array with two arrays in it get merged into a single array. 在Perl中,一个包含两个数组的数组将合并为一个数组。 You want references for the internal arrays if you don't want them concatenated.
如果不希望它们连接,您需要内部数组的引用。 Here's a dump of your code:
这是您的代码转储:
use strict;
use Data::Dumper;
my @frame_events = (((1) x 10), ((1) x 10));
print Dumper(\@frame_events);
result: 结果:
$VAR1 = [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
];
and if you switch to array reference creators, brackets instead of parents, with this code: 如果你切换到数组引用创建者,括号而不是父代,使用此代码:
use strict;
use Data::Dumper;
my @frame_events = ([(1) x 10], [(1) x 10]);
print Dumper(\@frame_events);
you get this: 你得到这个:
$VAR1 = [
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
],
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
];
The quickest way is to use the push command. 最快的方法是使用push命令。
$size = 10; $ size = 10; push @matrix, [(0)x$size] for (0..$size);
推送@matrix,[(0)x $ size]为(0 .. $ size);
This will create a 10x10 array initialized with zeros. 这将创建一个用零初始化的10x10数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.