On 30 Apr 2007 23:22:51 -0700,
<> wrote:
> Hi,
>
> The only way I could get arrays to work with OOP in perl was to use a
> reference to an array. I am wondering is this safe - ie is there any
> chance that some part of the array may get overwritten in memory since
> I am just using the reference in the functions? What is the best way
> to do this?
I'm wondering what exactly you mean by 'get arrays to work'. Arrays
don't work. They're used to store data.
> I tried assigning $self->{'data_array'} = ("MON","TUE","WED"), but
> then I found when I try to access this data, the array gets messed up
> and it comes out as a scalar or as the last value in the array.
Ah.
There is indeed some confusion in your head about what arrays are.
$self->{'data_array'} is a scalar. It is a single element out of a hash,
which is accessed via a reference to it, stored in $self. It cannot be
an array, because all you can store in a scalar, is a scalar. When you
assign a list to a scalar, you end up with the last element in the
scalar.
A lot of this is explained int he perlref documentation. It addresses
building complex data structures (which Perl objects most often are)
with references.
As an example:
If you want to store an array in a complex data structure, you do indeed
do that by storing a reference to the array. You can do that in several
ways:
# Store a reference to an anonymous array
my $foo = [1, 2, 3];
# Set $foo to the value 3, ignoring the other elements in the list
$foo = (1, 2, 3);
# access the first element
my $bar = $foo->[0];
# Store a reference to a named array
my @ar = (1, 2, 3);
$foo = \@ar;
I have the vague feeling that you're looking for the anonymous array
syntax.
Martien
--
|
Martien Verbruggen | Begin at the beginning and go on till you
| come to the end; then stop.
|