[Brisbane-pm] Counting elements in a 2D array

Damian James djames at thehub.com.au
Thu Mar 1 20:23:47 PST 2007


On 02/03/2007, at 1:44 PM, Martin Jacobs wrote:

> Hi folks,
>
> How do I count the number of elements in a 2D array.
>
> I have an array called @rainrecord, which has a number of elements  
> $rainrecord[x][y].
>

You have an array @rainrecord, each element of which contains a  
reference to an anonymous array, so $rainrecord[x] gives a reference  
to the array stored at that point. You'll find it less confusing if  
you dereference explicitly:

   $rainrecord[x]->[y];

Here it's plain that x is an index of the array, while y is the index  
of the reference to the anonymous array in $rainrecord[x]. It might  
seem strange, and it may take a while to sink in why you'd want to do  
this. The underlying reason is that Perl doesn't really do "2D  
arrays". What it does provide is a mechanism that lets you create  
arrays containing references to other (optionally anonymous) arrays.  
They aren't the same thing, and behave somewhat differently. 2D  
arrays are a matrices, while what Perl provides are recursive  
directed graphs.

> If I do
>
> $Last_line_in_Rainfall_data_array = $#rainrecord;
>
> It returns '7'. It looks to me that this is the number of 'x'  
> entries - 'x' goes from 0 to 7, whereas 'y' could be anything.
>
> How do I get it to return the number of 'y' entries?

The question only makes sense if you always have the same number of y  
entries in every x.

How about (untested, so please don't run it as `sudo scriptname.pl > / 
boot/vmlinuz-2.4.27.3.386` or anything):
my @rainrecord;
for ( 0..7) { $rainrecord[$_] = [ 0 .. int rand 100] };
for my $x ( 0 .. $#rainrecord ) {
   printf  "x = %3s;  last index of y = %5s; number of elements in y  
= %5s\n" ,
     $x, $#{ $rainrecord[$x] },  scalar @{ $rainrecord[$x]  };
}

or if you just want the max y:

my $max_y;
for ( @rainrecord ) { $max_y = $#{ $_ } if $#{$_} > $max_y }
print "$max_y\n";

Note that here the dereferencing is all explicit (even if the syntax  
is a bit ungainly).

Cheers,
Damian


More information about the Brisbane-pm mailing list