Finding multidimensional array size

multidimensional-array, perl

Solution

This is wrong:

my @myarr = [
                [ "itemone", "itemoneb", "itemonec" ],
                [ "itemtwo", "itemtwob", "itemtwoc" ]
               ];

It should be either:

my $myarr = [
                [ "itemone", "itemoneb", "itemonec" ],
                [ "itemtwo", "itemtwob", "itemtwoc" ]
               ];

It is "$myarr" above. The square bracket will return a reference to a list which is a scalar. Hence need to use "$" instead of "@".

Or

my @myarr = (
                [ "itemone", "itemoneb", "itemonec" ],
                [ "itemtwo", "itemtwob", "itemtwoc" ]
               );

It is "()" above instead of "[]". The "()" will return the list and hence it needs "@".

Check the below code which iterates over the AoA. This way you can access all the elements of the AoA. As well as individual elements:

#!/usr/bin/perl -w
use strict;

my @mynames = (
                [ "myname", "mydescription", "mydata"],
                [ "myname2", "mydescription2", "mydata2"],
                [ "myname3", "mydescription3", "mydata3"],
              );

### To access all the elements in above AoA
foreach my $a (@mynames)
{
    foreach my $b ( @{$a} )
    {
        print $b."\t";
    }
    print "\n";
}
print "====================================\n";

### To access individual elements:
print $mynames[1][2]."\n"; ### It prints mydata2

You may want to read perlref to learn and understand Perl reference and nested data structure.

Problem

What is the difference when you use `()` in Perl versus `[]` for example and how do you find the size of the array when it uses the square brackets? ``` my @myarr = ( # Parenthesis [ "itemone", "itemoneb", "itemonec" ], [ "itemtwo", "itemtwob", "itemtwoc" ] ); my @myarr = [ # Square bracket [ "itemone", "itemoneb", "itemonec" ], [ "itemtwo", "itemtwob", "itemtwoc" ] ]; ``` Thank you for the explanations. I am still trying to understand this, and it's just slightly confusing to me at the moment. I still can't figure out how to iterate through my data here: ``` #!/usr/bin/perl -w use strict; use FindBin qw($Bin); use Cwd; use Data::Dumper; my @mynames = ( [ "myname", "mydescription", "mydata"], [ "myname2", "mydescription2", "mydata2"], [ "myname3", "mydescription3", "mydata3"], ); go(); sub go { start(\@mynames); } sub start { my @input_name = shift; # This works #print @input_name->[0][0][0]; #die; # This Shows #print Dumper(@input_name); #$VAR1 = [ # [ # 'myname', # 'mydescription', # 'mydata' # ], # [ # 'myname2', # 'mydescription2', # 'mydata2' # ], # [ # 'myname3', # 'mydescription3', # 'mydata3' # ] # ]; # How do I iterate? #for my $i (0..@$input_name) { # my $name = ""; # my $description = ""; # my $data = ""; # #} } ```

Original source

Related problems