[Wellington-pm] Referencing arrays in an object

Grant McLean grant at mclean.net.nz
Sun May 28 00:35:46 PDT 2006

On Sun, 2006-05-28 at 17:39 +1200, Cliff Pratt wrote:
> One of the methods is called 'grid' initialised so:
> $self->grid([]) ;
> I can access the elements of the array referred to by $self->grid by the 
> following:
> $xxxx = $self->grid->[$i] ; # Within a method of the class
> I'm not using any accessor method here, am I? 

Yes, you are.  $self->grid is calling the 'grid' accessor which is
returning an array reference.  You are then indexing into the referenced
array by appending ->[$i]

If you wanted to foreach through all the elements in the array you could
do it like this:

  foreach my $cell ( @{ $self->grid } ) {
    # do something with $cell

> I theenk that the accessor 
> method will be something like the following:
> $xxxx = $self->grid([$i]) ; # Will this work?

No, in this case you're calling the grid method and passing it a
reference to a newly created array with one element, which contains the
current value of $i.  From what you said earlier, the effect will be
overwriting the whole 'grid' array.

You could conceivably write your own accessor method that took the grid
index as an argument:


It's hard to say whether that would offer any advantage in your case.


More information about the Wellington-pm mailing list