Accessor Methods for Arrays in Perl
I have an object that stores arrays as instance variables. Since Perl does not seem to support this, I have to store references to the arrays instead. However, I cannot figure out how to mutate these arrays once they have been created; the methods seem to change only the local copy. (Currently, at the end of addOwnedFile(), the object data is unchanged).
sub new {
my ($class) = @_;
my @owned_files = ();
my @shared_files = ();
my $self = {
#$[0] is the class
_name => $_[1],
_owned_files => \[],
_shared_files => \[],
};
bless $self, $class;
return $self;
}
#Add a file to the list of files that a user owns
sub addOwnedFile {
my ($self, $file) = @_;
my $ref = $self -> {_owned_files};
my @array = @$ref;
push(@array, $file);
push(@开发者_如何转开发array, "something");
push(@{$self->{_owned_files}}, "something else");
$self->{_owned_files} = \@array;
}
The code you posted triggers a runtime "Not an ARRAY reference..." error. The reason is that sets _owned_files
to \[]
which is not an array reference but rather a reference to an array reference. Drop the \
from both array attributes.
With that out of the way, we can get to the next problem. @array
is a copy of the anonymous array held by the object. Your first two push
es are to the copy, the last to the held array. You then clobber the held array by replacing it with a reference to the copy. It's best to just work with the original array via the reference. Either of the following would work:
push @$ref, 'something';
push @{$self->{_owned_files}}, 'something';
And drop the
$self->{_owned_files} = \@array;
at the end.
sub new {
my $class = shift;
my $name = shift;
my $self = {
_name => $name,
_owned_files => [],
_shared_files => [],
};
return bless $self, $class;
}
sub addOwnedFile {
my ($self, $file) = @_;
push @{$self->{_shared_files}}, $file;
}
I'm fairly sure the issue you have in in the
my $self = {
#$[0] is the class
_name => $_[1],
_owned_files => \[],
_shared_files => \[],
};
section. _owned_file=> \[]
will not create and array reference but rather a reference to a reference to an array. Rather what you want is _owned_files => []
. Same for shared files.
精彩评论