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

Suppose that @mat is a matrix with dimension 4x5 (4 rows and 5 columns)
if I use $rows=@mat I can get the number of rows.
Is there something similar to extract the number of cols?
If not how can I do that considering that not every element of the matrix is set to a value?

Replies are listed 'Best First'.
Re: How to extract the number of cols from a matrix?
by Zaxo (Archbishop) on Jun 26, 2005 at 07:59 UTC

    If the rows of a matrix are well-constructed, each will have the same number of elements, even if some elements are undefined. my $cols = @{$mat[0]}; To check for that goodness,

    @mat == grep { @{$_} == @{$mat[0]}; } @mat or die '@mat not well-formed';
    The equality tests put all those arrays in scalar context, so their counts are what is tested.

    See tye's References quick reference for a concise key to understanding reference manipulations.

    After Compline,
    Zaxo

      Instead of counting the well-formed rows when trying to determine the existence of malformed rows, I'd count the malformed ones. In effect, you're using double negation ("no not well-formed rows"), which is less clear than the straightforward approach.

      die '@mat malformed' if grep { @{$_} != @{$mat[0]} } @mat;
Re: How to extract the number of cols from a matrix?
by rev_1318 (Chaplain) on Jun 26, 2005 at 13:08 UTC
    Actually, $rows = @mat will only give you the current number of rows. The fact that is is a 4x5 matrix follows only from your definition, not from the array of arrays. If not all elements are set, you can only get the current dimensions, which may differ from your assumed definition...

    Paul