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

I know that the code for the size of an array is

$size = @array_name
but how do you get the size of a row (?) of a 2D array

I have tried ...

$size = @array_name[2] and $size = $array_name[2]
Running out of ideas, and can't find it in a book anywhere

Replies are listed 'Best First'.
Re: how to get the size of a 2D array
by davorg (Chancellor) on Jun 29, 2001 at 13:24 UTC

    The trick is to realise that there is no such thing as a 2D array in Perl. It's actually an array where the elements are references to a other arrays. Therefore $array_name[2] contains the reference to the array and @{$array_name[2]} gives you the referenced array. To get the size of this array simply evaluate it in a scalar context as always.

    $size = @{$array_name[2]};

    You might like to take a look at the perlreftut, perllol and perldsc manual pages for more information.

    --
    <http://www.dave.org.uk>

    Perl Training in the UK <http://www.iterative-software.com>

Re: how to get the size of a 2D array
by agoth (Chaplain) on Jun 29, 2001 at 13:24 UTC
    look at:
    my @ary = ( [12,13,14,15], [67,68,69,70,71]); print scalar(@{ $ary[1] }); $var = @{ $ary[1] }; print $var;
(ar0n) Re: how to get the size of a 2D array
by ar0n (Priest) on Jun 29, 2001 at 17:15 UTC
    ... and if you want the total number of elements in a 2d array:
    use List::Util qw/sum/; my $num = sum map scalar @{$_}, @array;


    ar0n ]

      i like it, or:
      $num += scalar @{$_} for @array;
      :)
Re: how to get the size of a 2D array
by fenonn (Chaplain) on Jun 29, 2001 at 16:36 UTC
    Another alternative to get the size of the second array would be:
    $#{$array_name[2]}+1

      That only works as long as no-one has changed the value in $[. I know that no-one should be playing with that value, but it's always possible that they have.

      Why use a potentially inaccurate method, when a simpler, accurate one exists?

      --
      <http://www.dave.org.uk>

      Perl Training in the UK <http://www.iterative-software.com>

Re: how to get the size of a 2D array
by richmusk (Novice) on Jun 29, 2001 at 13:27 UTC
    Thanks guys ... sorted !!!