smist has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks. I'm having problems understanding why the print statement below prints "-1" I would have thought it would print "2" Can someone enlighten me please?
Thanks!
my @array1 = qw(one two three four five); my @array2 = qw(blue green white orange black); my @array3 = qw(car bike plane ship); my @array_ref = (\@array1, \@array2, \@array3); print $#{$array_ref};

Replies are listed 'Best First'.
Re: Dereferencing an array of arrays
by ikegami (Patriarch) on Oct 22, 2007 at 17:02 UTC

    use strict; identifies your error. Your getting the index of the last element in the array referenced by $array_ref, but $array_ref doesn't exist.

    use strict; use warnings; my @array1 = qw(one two three four five); my @array2 = qw(blue green white orange black); my @array3 = qw(car bike plane ship); my @array_of_refs = (\@array1, \@array2, \@array3); print $#array_of_refs; # 2 print $#{ $array_of_refs[2] }; # 3 = $#array3
      Thank you. I think I get it now. :-)
Re: Dereferencing an array of arrays
by kyle (Abbot) on Oct 22, 2007 at 17:09 UTC

    You might want this:

    my $array_ref = [ \@array1, \@array2, \@array3 ]; print $#{$array_ref};

    Your @array_ref is not a reference to an array. It's an array full of references. The $array_ref I've shown above is an array reference.

      Thanks Kyle. That helped to clear it up for me.
Re: Dereferencing an array of arrays
by johngg (Canon) on Oct 22, 2007 at 18:17 UTC
    If you don't need the intermediate arrays (@array1, @array2 and @array3), you can save yourself some typing by constructing your array of arrays (or a ref. to an array of arrays) in one go.

    # Array of arrays. # my @arrayOfArrays = ( [ qw(one two three four five) ], [ qw(blue green white orange black) ], [ qw(car bike plane ship) ], ); # Reference to array of arrays, # my $refToArrayOfArrays = [ [ qw(one two three four five) ], [ qw(blue green white orange black) ], [ qw(car bike plane ship) ], ];

    I hope this is of use.

    Cheers,

    JohnGG

Re: Dereferencing an array of arrays
by TGI (Parson) on Oct 22, 2007 at 19:05 UTC

    If you haven't read it yet, check out the Data Structures Cookbook. It's chock full of nice examples of various nested data structures.

    When you are learning to work with nested structures, a pretty printer can be very handy. Since Data::Dumper is part of the default install, you've got one on hand and ready to use. Try this out:

    use strict; use warnings; use Data::Dumper; my @arrayOfArrays = ( [ qw(one two three four five) ], [ qw(blue green white orange black) ], [ qw(car bike plane ship) ], ); print Dumper \@arrayOfArrays;


    TGI says moo