Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a 2D array in Perl?

Tags:

arrays

perl

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.

like image 336
Mark Avatar asked Mar 13 '10 02:03

Mark


3 Answers

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:

  • arrays of arrays (of arrays ...)
  • arrays of hashes (of ...)
  • hashes of arrays
  • hashes of hashes.

You can have:

  • arrays of references to arrays (of references to arrays ...)
  • arrays of references to hashes (of references to ...)
  • hashes of references to arrays
  • hashes of references to hashes

You can also have:

  • arrays of scalars
  • arrays of references of arrays of scalars
  • arrays of references of arrays of references of arrays of scalars
  • arrays of references of hashes of scalars
  • etc.
like image 158
vladr Avatar answered Oct 17 '22 15:10

vladr


See also Array of Arrays in Perl Data Structures Cookbook.

like image 7
Sinan Ünür Avatar answered Oct 17 '22 16:10

Sinan Ünür


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
          ]
        ];
like image 2
Ry4an Brase Avatar answered Oct 17 '22 15:10

Ry4an Brase