[ale] Private members in perl

Fletch fletch at phydeaux.org
Sun Aug 1 19:52:05 EDT 2004


>>>>> "Chris" == Chris Fowler <cfowler at outpostsentinel.com> writes:


[...]
    Chris>   my @ARA = {}; 
    Chris>   my $ref = \@ARA;
    Chris>
    Chris>   bless $ref, $class;
    Chris>   return $ref;
    Chris> }

OK, you've made an array @ARA which contains a single element (that
single element being a reference to an anonymous hash) and then you
return a blessed reference to that array.  You probably mean to just
have a new empty array and return a reference to that (my @self;
return bless \@self, $class;) or you want to use the anonymous
arrayref constructor (my $self = []; return bless $self, $class).


    Chris> sub get_num { my $self = shift; my @W = $self; return $#W;
    Chris> }

Your instance is an array ref, so presuming you want to return the
number of elements contained therein you probably want:


sub get_num { return scalar @{ shift() } }


Or more verbosely:


sub get_num {
  my $self = shift;

  my $num_elems = @{ $self };

  return $num_elems;
}


If you really want the index of the last element (which is what you
were getting; the number of elements in an array is obtained by using
the array in a scalar context (either explicitly as in the first case
or implicitly as in the second)) you would use $#{ shift() } (or $#{
$self } in the verbose version).


    Chris> sub append { my $self = shift; push @{$self}, shift;
    Chris> }

This should work fine; I'd bet it's the problem with the get_num being
broken that's making it look like its empty.  When in doubt, it can
help to use Data::Dumper or YAML to dump out what your instances look
like under the hood (or even just use the x command in the debugger).

-- 
Fletch                | "If you find my answers frightening,       __`'/|
fletch at phydeaux.org   |  Vincent, you should cease askin'          \ o.O'
                      |  scary questions." -- Jules                =(___)=
                      |                                               U



More information about the Ale mailing list