How do I initialize a 2D array in Perl?
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.
This syntax only seems to initialize a 1D array as print "$frame_events[1]\n" works. Though Perl doesn't give any error during the assignment.
You cannot have an array of arrays in Perl, only an array of references to arrays.
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:
See also Array of Arrays in Perl Data Structures Cookbook.
In Perl an array with two arrays in it get merged into a single array. 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
]
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With